【问题标题】:Add commas to decimal column without rounding off将逗号添加到小数列而不四舍五入
【发布时间】:2022-01-21 17:08:24
【问题描述】:

我有一个名为 Price_col 的 pandas 列。看起来像这样。

       Price_col
    1. 1000000.000
    2. 234556.678900
    3. 2345.00
    4.
    5. 23.56

我正在尝试在我的 Price_col 中添加逗号以使其看起来像这样。

       Price_col
    1. 1,000,000.000
    2. 234,556.678900
    3. 2,345.00
    4.
    5. 23.56

当我尝试转换值时,它总是四舍五入。有没有办法让我在不四舍五入的情况下获得原始价值。

我尝试了下面的代码。这是我得到的价值 234556.678900。

n = "{:,}".format(234556.678900)
print(n)
>>> 234,556.6789

【问题讨论】:

    标签: python dataframe decimal


    【解决方案1】:

    为定点添加f

    >>> "{:,}".format(234556.678900)
    '234,556.6789'
    >>> "{:,f}".format(234556.678900)
    '234,556.678900'
    

    您还可以使用 .p 控制精度,其中 p 是位数(并且可能应该这样做).. 注意,当您处理浮点数时,您将拥有一些IEEE 754 aliasing,尽管无论支持数据如何,通过格式表示应该都很好

    >>> "{:,.5f}".format(234556.678900)
    '234,556.67890'
    >>> "{:,.20f}".format(234556.678900)
    '234,556.67889999999897554517'
    

    完整的迷你语言格式规范可以在这里找到:
    https://docs.python.org/3/library/string.html#format-specification-mini-language

    【讨论】:

    • 非常感谢,有没有一种方法可以在单个语句中将其应用于整个列,而无需逐个循环和更改值。
    【解决方案2】:

    从您的评论中,我意识到您可能真的想要How to display pandas DataFrame of floats using a format string for columns? 中描述的其他内容,并且只更改数据的视图

    创建一个新的 string 格式化为字符串的列

    >>> df = pd.DataFrame({"Price_col": [1000000.000, 234556.678900, 2345.00, None, 23.56]}
    >>> df["price2"] = df["Price_col"].apply(lambda x: f"{x:,f}")
    >>> df
          Price_col            price2
    0  1000000.0000  1,000,000.000000
    1   234556.6789    234,556.678900
    2     2345.0000      2,345.000000
    3           NaN               nan
    4       23.5600         23.560000
    >>> df.dtypes
    Price_col    float64
    price2        object
    dtype: object
    

    暂时更改数据的显示方式

    >>> df = pd.DataFrame({"Price_col": [1000000.000, 234556.678900, 2345.00, None, 23.56]}
    >>> print(df)
          Price_col
    0  1000000.0000
    1   234556.6789
    2     2345.0000
    3           NaN
    4       23.5600
    >>> with pd.option_context('display.float_format', '€{:>18,.6f}'.format):
    ...     print(df)
    ... 
                Price_col
    0 €  1,000,000.000000
    1 €    234,556.678900
    2 €      2,345.000000
    3                 NaN
    4 €         23.560000
    >>> print(df)
          Price_col
    0  1000000.0000
    1   234556.6789
    2     2345.0000
    3           NaN
    4       23.5600
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多