can*_*ord 11 python csv decimal type-conversion pandas
我正在使用pandas(v0.18.1)从名为'test.csv'的文件中导入以下数据:
a,b,c,d
1,1,1,1.0
Run Code Online (Sandbox Code Playgroud)
我已经为列'c'和'd'将dtype设置为'decimal.Decimal',而是将它们作为'str'类型返回.
import pandas as pd
import decimal as D
df = pd.read_csv('test.csv', dtype={'a': int, 'b': float, 'c': D.Decimal, 'd': D.Decimal})
for i, v in df.iterrows():
print(type(v.a), type(v.b), type(v.c), type(v.d))
Run Code Online (Sandbox Code Playgroud)
结果:
`<class 'int'> <class 'float'> <class 'str'> <class 'str'>`
Run Code Online (Sandbox Code Playgroud)
我也尝试在导入后显式转换为十进制没有运气(转换为浮点数但不是十进制数).
df.c = df.c.astype(float)
df.d = df.d.astype(D.Decimal)
for i, v in df.iterrows():
print(type(v.a), type(v.b), type(v.c), type(v.d))
Run Code Online (Sandbox Code Playgroud)
结果:
`<class 'int'> <class 'float'> <class 'float'> <class 'str'>`
Run Code Online (Sandbox Code Playgroud)
下面的代码将'str'转换为'decimal.Decimal',所以我不明白为什么pandas的行为方式不同.
x = D.Decimal('1.0')
print(type(x))
Run Code Online (Sandbox Code Playgroud)
结果:
`<class 'decimal.Decimal'>`
Run Code Online (Sandbox Code Playgroud)
jez*_*ael 13
我认为你需要转换器:
import pandas as pd
import io
import decimal as D
temp = u"""a,b,c,d
1,1,1,1.0"""
# after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp),
dtype={'a': int, 'b': float},
converters={'c': D.Decimal, 'd': D.Decimal})
print (df)
a b c d
0 1 1.0 1 1.0
for i, v in df.iterrows():
print(type(v.a), type(v.b), type(v.c), type(v.d))
<class 'int'> <class 'float'> <class 'decimal.Decimal'> <class 'decimal.Decimal'>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8472 次 |
| 最近记录: |