gpt4 book ai didi

python - 小数点/千位分隔符的 pd.read_feather 问题和 float 的舍入问题

转载 作者:行者123 更新时间:2023-12-03 14:42:29 28 4
gpt4 key购买 nike

我想使用 .ftr 文件来快速分析数百个表。不幸的是,我在十进制和千位分隔符方面遇到了一些问题,类似于 that post ,只是 read_feather 不允许 decimal=',', thousands='.'选项。我尝试了以下方法:

df['numberofx'] = (
df['numberofx']
.apply(lambda x: x.str.replace(".","", regex=True)
.str.replace(",",".", regex=True))

导致
AttributeError: 'str' object has no attribute 'str'

当我把它改成
df['numberofx'] = (
df['numberofx']
.apply(lambda x: x.replace(".","").replace(",","."))

我在结果中收到一些奇怪的(四舍五入)错误,例如对于某些高于 1k 的数字,使用 22359999999999998 而不是 2236。所有低于 1k 的都是真实结果的 10 倍,这可能是因为删除了“.”。的浮点数并创建该数字的 int。


df['numberofx'] = df['numberofx'].str.replace('.', '', regex=True)

也会导致结果中出现一些奇怪的行为,因为有些数字在 10^12 中,而其他数字则应保持在 10^3 中。

Here is how I create my .ftr files from multiple Excel files .我知道我可以简单地从 Excel 文件创建数据帧,但这会大大减慢我的日常计算速度。

我该如何解决这个问题?

编辑 :问题似乎来自于将 excel 文件作为 df 读取,关于小数点和千位分隔符的非美国标准,而不是将其保存为 Feather 。使用 pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.')在 excel 文件中读取的选项解决了我的问题。这就引出了下一个问题:

为什么在 Feather 文件中保存浮点数会导致奇怪的舍入错误,例如将 2.236 更改为 2.2359999999999998?

最佳答案

您的代码中的问题是:

当您检查数据框( Panda )中的列类型时,您会发现:

df.dtypes['numberofx']

结果:输入 object
所以建议的解决方案是尝试:
df['numberofx'] = df['numberofx'].apply(pd.to_numeric, errors='coerce')

解决此问题的另一种方法是将您的值转换为浮点数:
def coerce_to_float(val):
try:
return float(val)
except ValueError:
return val

df['numberofx']= df['numberofx'].applymap(lambda x: coerce_to_float(x))

为了避免这种类型的浮点 '4.806105e+12',这里是一个示例
sample :
df = pd.DataFrame({'numberofx':['4806105017087','4806105017087','CN414149']})
print (df)
ID
0 4806105017087
1 4806105017087
2 CN414149

print (pd.to_numeric(df['numberofx'], errors='coerce'))
0 4.806105e+12
1 4.806105e+12
2 NaN
Name: ID, dtype: float64

df['numberofx'] = pd.to_numeric(df['numberofx'], errors='coerce').fillna(0).astype(np.int64)
print (df['numberofx'])
ID
0 4806105017087
1 4806105017087
2 0

关于python - 小数点/千位分隔符的 pd.read_feather 问题和 float 的舍入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61909652/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com