如何获得熊猫数据框每一列中的小数位数的最大值?

时间:2020-04-27 01:21:18

标签: python pandas floating-point precision

我需要将全局浮点精度设置为可能的最小值

此外,我需要获得每一列的精度,部分是为了获得全局精度,另一方面,我想为用户为每列使用尽可能多的小数位。

我从CSV获取数据。首先,我将所有单元格加载为字符串。转换为数字后,这些列可能具有不同的dtype。

在整数列(不带“。”)中,没有任何NaN值。因此,我认为我可以在数据框包含字符串的情况下进行复制,并将数字除以'。字符。因为如果单元格已经有浮点数,我将无法获得小数位数,因为我会得到类似this5.55 % 1 >> 0.550000000001的信息。我的意思是有时python仅输出机器存储的二进制近似值的decimal approximation to the true decimal value。然后,我知道不可能准确地获取十进制值。

没有所有值为NaN的列

import pandas as pd

pd.set_option('precision', 15)  # if > 15 the precision is not working well

df = pd.DataFrame({
    'x':['5.111112222233', '5.111112222', '5.11111222223', '5.2227', '234', '4', '5.0'],
    'y':['ÑKDFGÑKL', 'VBNVBN', 'GHJGHJ', 'GFGDF', 'SDFS', 'SDFASD', 'LKJ'],
    'z':['5.0', '5.0', '5.0', '5.0', '3', '6', '5.0'],
    'a':['5', '5', '5', '5', '3', '6', '9'],
    'b':['5.0', '5.0', '5.0', '5.0', '3.8789', '6', np.nan],
})

df_str = df.copy(deep=True)
df = df.apply(lambda t: pd.to_numeric(t, errors='ignore', downcast='integer'))

precisions = {}
pd_precision = 0

# Float columns
for c in df.select_dtypes(include=['float64']):
    p = int(df_str[c].str.rsplit(pat='.', n=1, expand=True)[1].str.len().max())  # always has one '.'
    if p > pd_precision:
        pd_precision = p
    precisions[c] = p

# Integer columns
for c in df.select_dtypes(include=['int8', 'int16', 'int32', 'int64']):
    precisions[c] = 0

# String and mixed columns
for c in df.select_dtypes(include=['object']):  # or exclude=['int8', 'int16', 'int32', 'int64', 'float64']
    precisions[c] = False

if pd_precision > 15:
    pd_precision = 15

pd.set_option('precision', pd_precision)  # pd_precision = 12
precisions  # => {'x': 12, 'b': 4, 'z': 0, 'a': 0, 'y': False}

我知道有一个Decimal类,但是我相信我会失去带浮点数的熊猫数据帧性能的所有好处。

是否有更好的方法来获取小数位数?

0 个答案:

没有答案