首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >pandas.DataFrame.to_markdown变换大整数到浮点

pandas.DataFrame.to_markdown变换大整数到浮点
EN

Stack Overflow用户
提问于 2020-12-25 13:36:08
回答 2查看 914关注 0票数 2

pandas.DataFrame.to_markdown将大型int转换为float。它是一个bug还是一个特性?有什么解决办法吗?

代码语言:javascript
运行
复制
>>> 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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-25 14:09:31

我最初只找到了一个解决办法,但没有找到解释:将列转换为字符串。

代码语言:javascript
运行
复制
>>> df = pd.DataFrame({"A": [1234567, 1234567]})
>>> df["A"] = df.A.astype(str)
>>> print(df.to_markdown())
|    |       A |
|---:|--------:|
|  0 | 1234567 |
|  1 | 1234567 |

更新:

我认为这是由两个因素造成的:

  • _column_type函数在tabulate中的应用
代码语言:javascript
运行
复制
def _column_type(strings, has_invisible=True, numparse=True):
    """The least generic type all column values are convertible to.

可以通过tablefmt="pretty"禁用转换来解决这个问题。

代码语言:javascript
运行
复制
print(df.to_markdown(tablefmt="pretty"))
+---+---------+
|   |    A    |
+---+---------+
| 0 | 1234567 |
| 1 | 1234567 |
+---+---------+
  • 当有多个列时,其中一个列包含float编号。由于tabulate使用df.values提取数据,从而将DataFrame转换为numpy.array,因此所有值都被转换为相同的dtype (float)。这一点在本期中也有讨论。
代码语言:javascript
运行
复制
>>> 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]])
票数 2
EN

Stack Overflow用户

发布于 2020-12-25 14:17:08

如果您检查熊猫选项,那么重要数字的默认数字是6。

代码语言:javascript
运行
复制
import pandas as pd

pd.describe_option()

display.precision : int
    Floating point output precision (number of significant digits). This is
    only a suggestion
    [default: 6] [currently: 6]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65448556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档