【问题标题】:Set decimal precision of a pandas dataframe column with a datatype of Decimal设置数据类型为 Decimal 的 pandas 数据框列的小数精度
【发布时间】:2021-04-06 21:27:25
【问题描述】:

我有一个包含两列的 pandas 数据框,第 1 列包含文本,第 2 列包含十进制值。

Key Value
A 1.2089
B 5.6718
B 7.3084

我使用 '.apply' 函数将 value 列的数据类型设置为 Decimal(Python Decimal 库)。一旦我这样做了,值列就会从小数点后 4 位变为小数点后 43 位。我尝试使用 .getcontect.prec = 4 无济于事。

数据框是通过读取与上表格式相同的 CSV 文件构建的。值列中的所有小数只保留 4 位小数。

import pandas as pd
from decimal import *

def get_df(table_filepath):
    df = pd.read_csv(table_filepath)
    getcontect.prec = 4
    df['Value'] = df['Value'].apply(Decimal)

上面的代码是我尝试过的,但仍然导致输出的值列值有 43 个小数位,而不是从 csv 文件中读取的每个值应该有 4 个小数位。

我打印数据框时得到的结果是:

Key Value
A 1.20890000000003046807250939309597015380859375
B 5.67180000000000318323145620524883270263671875
B 7.30838399999999969077180139720439910888671875

我只想要 4 位小数的精度,因为这些值稍后将用于进行一些数学运算,并且我想使用我提供的确切值。

【问题讨论】:

    标签: python pandas decimal


    【解决方案1】:

    这可以通过更改浮点数的打印选项来修改,但是它将修改每个浮点数据类型的打印方式

    pd.set_option('display.float_format', '{:.10f}'.format)
    

    请记住,这只是它的打印方式。该值存储在数据框中,每个小数点。

    另一方面,您可以通过以下方式限制小数:

    df.Value = df.Value.round(4)
    

    但这将根据小数点后五位四舍五入。最后一个选项是使用np.ceilnp.floor,但由于这不支持小数,因此需要使用乘法和除法的方法:

    precision = 4
    df['Value_ceil'] = np.ceil(df.Value * 10**precision) / (10**precision)
    df['Value_floor'] = np.floor(df.Value * 10**precision) / (10**precision)
    

    【讨论】:

    • .round 函数不起作用,它给出错误 TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'。为了澄清 Value 列已设置为名为 Decimal 的数据类型,并且不是用于在 python 中表示小数的默认浮点类型。
    • 不要将数据类型转换为十进制,将 ti 保留为来自 read_csv 的浮点数
    • 我必须使用 Decimal 因为使用浮点数缺乏精度会导致以后出现问题(例如在值 x=b 之间进行比较时)
    • 可能有直接使用十进制的方法,但我不知道答案。在这种情况下,我会修改浮点数,然后将其转换为十进制。
    【解决方案2】:

    修复了这个问题,似乎与 Decimal 如何从浮点数转换为十进制数有关。将 Values 列设置为数据类型字符串,然后转换为 Decimal 得到了我想要的结果。

    def get_df(table_filepath):
        df = pd.read_csv(table_filepath)
        df['Value'] = df['Value'].apply(str) 
        df['Value'] = df['Value'].apply(Decimal)
    
    Key Value
    A 1.2089
    B 5.6718
    B 7.3084

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      相关资源
      最近更新 更多