我想针对我在 pandas.read_csv 例程中注意到的问题寻求补救步骤的指导。当我使用 pd.to_csv 将长整数存储到文件中时,它可以很好地存储数据 - 但是当我使用 pd.read_csv 读回它时,它会弄乱最后 3 位数字。当我尝试使用 to_csv (不进行任何编辑)再次将其保存回来时,生成的 CSV 文件中的数字与原始 CSV 文件不同。我在下面说明了这个问题(注意 4321113141090630389 如何变为 4321113141090630400 以及 4321583677327450765 如何变为 4321583677327450880):
由 pd.to_csv 创建的原始 CSV 文件:
grep -e 321583677327450 -e 321113141090630 orig.piece
orig.piece:1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765
orig.piece:5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389
import pandas as pd
import numpy as np
orig = pd.read_csv('orig.piece')
orig.dtypes
Unnamed: 0 int64
aa object
act float64
...
...
s_act float64
dtype: object
>orig['s_act'].head(6)
0 NaN
1 4.321584e+18
2 4.321974e+18
3 4.321494e+18
4 4.321283e+18
5 4.321113e+18
Name: s_act, dtype: float64
>orig['s_act'].fillna(0).astype(int).head(6)
0 0
1 4321583677327450880
2 4321973950881710336
3 4321493786516159488
4 4321282586859217408
5 4321113141090630400
>orig.to_csv('convert.piece')
grep -e 321583677327450 -e 321113141090630 orig.piece convert.piece
orig.piece:1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765
orig.piece:5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389
convert.piece:1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4.321583677327451e+18
convert.piece:5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4.3211131410906304e+18
您能帮我理解为什么 read_csv 会混淆最后三位数字吗?它甚至不是舍入问题,数字完全不同(例如上面的 4321583677327450765 变成 4321583677327450880)是因为科学记数法的阻碍 - 我们如何禁用它并让 pandas 将此数据视为对象/字符串或计划整数/浮点?
最佳答案
这是浮点错误。由于 s_act
列有缺失值(pandas 没有整数缺失值),因此它会使用 dtype=float 读取 s_act
(dtypes 在列级别定义) Pandas )。所以你基本上会看到以下内容:
>>> x = 4321113141090630389
>>> float(x)
4.32111314109063e+18
>>> int(float(x))
4321113141090630144
就解决方案而言,您可以在读取时将 s_act
的 dtype 更改为字符串(生成的 dtype 将是 oject)。例如:
data = """
id,val,x
1,4321113141090630389,4
2,,5
3,200,4
"""
df = pd.read_csv(StringIO(data),header=True,dtype={'val':str})
print df
id val x
0 1 4321113141090630389 4
1 2 NaN 5
2 3 200 4
print df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 0 to 2
Data columns (total 3 columns):
id 3 non-null int64
val 2 non-null object
x 3 non-null int64
df['val'] = df['val'].fillna(0).astype(int)
print df
id val x
0 1 4321113141090630389 4
1 2 0 5
2 3 200 4
关于python - pd.read_csv 的截断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23534775/