【问题标题】:pandas.DataFrame.to_markdown transform large int to floatpandas.DataFrame.to_markdown 将大整数转换为浮点数
【发布时间】:2020-12-25 13:36:08
【问题描述】:

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


    【解决方案1】:

    如果勾选 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]
    

    【讨论】:

    • 这并不能解释为什么int 值被转换为float
    【解决方案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)。 this issue 也对此进行了讨论。
    >>> 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]])
    

    【讨论】:

    • 我会暂时不接受这个答案,看看是否有人能提供比我自己更好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多