pandas:sum()返回无限值

问题描述 投票:-1回答:2

我有一个DataFrame,其列的数据类型是float16,最大值是65536.当我在pandas中调用sum()来汇总该列的所有值时,当值超出范围时,我得到无限的“inf”值。

这是输入数据的示例和sum的输出:

input sample and output

由于sum()函数的输出值的数据类型自动遵循列的数据类型,我想问一下是否有任何方法可以转换pandas中sum的值以避免不定式值?

python pandas sum infinite
2个回答
1
投票

第一个想到的是通过一个dtype=np.float64 param。

df.sum(axis=1,dtype=np.float64)

但是,这会返回ValueError:

ValueError:sum()的pandas实现中不支持'dtype'参数


可能的解决方法:

使用np.sum(),pandas的底层库,而不是传递dtype。

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'col1': [35000.0, 35000.0],
    'col2': [35000.0, 35000.0]
})

df['col1'] = df['col1'].astype(np.float16)
df['col2'] = df['col2'].astype(np.float16)

#print(df.sum(axis=1)) # --> results in inf 
#print(df.sum(axis=1,dtype=np.float64)) # --> results in error message
print(np.sum(df.values, dtype=np.float64, axis=1)) # --> works

1
投票

到目前为止还没有解决方案,可能的解决方法可能是@Anton vBR。但是,当在dtype float16的数据帧列上运行减少时,已经存在一个错误,它会产生令人惊讶的行为:

[已经在github上为此打开了一个Bug [(https://github.com/pandas-dev/pandas/issues/22841

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