pandas - pandas.DataFrame.to_markdown 将大整数转换为浮点数
问题描述
pandas.DataFrame.to_markdown
变int
大为float
. 它是错误还是功能?有什么解决办法吗?
>>> df = pd.DataFrame({"A": [123456, 123456]})
>>> print(df.to_markdown())
| | A |
|---:|-------:|
| 0 | 123456 |
| 1 | 123456 |
>>> df = pd.DataFrame({"A": [1234567, 1234567]})
>>> print(df.to_markdown())
| | A |
|---:|------------:|
| 0 | 1.23457e+06 |
| 1 | 1.23457e+06 |
>>> print(df)
A
0 1234567
1 1234567
>>> print(df.A.dtype)
int64
解决方案
我最初只找到了一种解决方法,但没有找到解释:将列转换为字符串。
>>> df = pd.DataFrame({"A": [1234567, 1234567]})
>>> df["A"] = df.A.astype(str)
>>> print(df.to_markdown())
| | A |
|---:|--------:|
| 0 | 1234567 |
| 1 | 1234567 |
更新:
我认为这是由2个因素引起的:
- 中的
_column_type
函数tabulate
:
def _column_type(strings, has_invisible=True, numparse=True):
"""The least generic type all column values are convertible to.
它可以通过禁用转换来解决tablefmt="pretty"
:
print(df.to_markdown(tablefmt="pretty"))
+---+---------+
| | A |
+---+---------+
| 0 | 1234567 |
| 1 | 1234567 |
+---+---------+
- 当有不止一列时,其中一列包含
float
数字。由于tabulate
用于df.values
提取数据,将 转换DataFrame
为numpy.array
,然后所有值都转换为相同的dtype
(float
)。这也在本期讨论。
>>> df = pd.DataFrame({"A": [1234567, 1234567], "B": [0.1, 0.2]})
>>> print(df)
A B
0 1234567 0.1
1 1234567 0.2
>>> print(df.A.dtype)
int64
>>> print(df.to_markdown(tablefmt="pretty"))
+---+-----------+-----+
| | A | B |
+---+-----------+-----+
| 0 | 1234567.0 | 0.1 |
| 1 | 1234567.0 | 0.2 |
+---+-----------+-----+
>>> df.values
array([[1.234567e+06, 1.000000e-01],
[1.234567e+06, 2.000000e-01]])
推荐阅读
- python-3.x - 如何使用 Python 创建包括图表在内的摊销表?
- netsuite - netsuite oneworld 客户声明
- graphql - 接口类型实现上的 GraphQL 查询片段
- r - R:难以生成 0 到 1 之间的正交多项式
- swift - 检测异步代码块的完成 - swift 4
- mysql - 前台的 ssh 隧道适用于 mysql 主机 localhost 和 127.0.0.1,但后台的 ssh-tunnel 不起作用
- ios - 如何拆分视频的前 15 秒并将其快速保存到相机胶卷
- java - 使用jsoup在html中检索跨度值
- c# - 使用另一种形式的文本框更新listviewitems c#
- python - 您如何创建一个根据列表中的顺序更改对象位置的类?