pandas.DataFrame.to_markdown 将大整数转换为浮点数

问题描述 投票:0回答:3

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
pandas markdown tabulate
3个回答
2
投票

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

>>> df = pd.DataFrame({"A": [1234567, 1234567]})
>>> df["A"] = df.A.astype(str)
>>> print(df.to_markdown())
|    |       A |
|---:|--------:|
|  0 | 1234567 |
|  1 | 1234567 |

更新:

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

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]])

0
投票

如果你检查 pandas 选项,默认有效位数是 6。

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
投票

正如 Marc 提到的,问题在于 tabulate 和 numpy 的类型转换。解决此问题的一种方法是强制 numpy 使用“对象”数据类型,它将把 numpy 数组中的所有内容存储为对象,而不是强制为通用数据类型,然后手动调用 tabulate:

>>> from tabulate import tabulate
>>> df = pd.DataFrame({"A": [1234567, 1234567], "B": [0.1, 0.2]})
>>> print(tabulate(df.to_numpy(dtype="object"), df.columns, tablefmt="pipe"))
|       A |   B |
|--------:|----:|
| 1234567 | 0.1 |
| 1234567 | 0.2 |

您也可以按照自己的喜好设置格式:

>>> print(tabulate(df.to_numpy(dtype="object"), df.columns, tablefmt="pipe", intfmt=",", floatfmt=".2f"))
|         A |    B |
|----------:|-----:|
| 1,234,567 | 0.10 |
| 1,234,567 | 0.20 |

请参阅制表了解更多选项。

© www.soinside.com 2019 - 2024. All rights reserved.