問題描述
我正在使用 pandas (v0.18.1) 從名為test.csv"的文件中導(dǎo)入以下數(shù)據(jù):
I am using pandas (v0.18.1) to import the following data from a file called 'test.csv':
a,b,c,d
1,1,1,1.0
我已將列 'c' 和 'd' 的 dtype 設(shè)置為 'decimal.Decimal' 但它們返回為類型 'str'.
I have set the dtype to 'decimal.Decimal' for columns 'c' and 'd' but instead they return as type '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))
結(jié)果:
`<class 'int'> <class 'float'> <class 'str'> <class 'str'>`
我還嘗試在導(dǎo)入后顯式轉(zhuǎn)換為十進制,但沒有成功(轉(zhuǎn)換為浮點有效但不是十進制).
I have also tried converting to decimal explicitly after import with no luck (converting to float works but not decimal).
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))
結(jié)果:
`<class 'int'> <class 'float'> <class 'float'> <class 'str'>`
以下代碼將str"轉(zhuǎn)換為decimal.Decimal",所以我不明白為什么 pandas 的行為方式不同.
The following code converts a 'str' to 'decimal.Decimal' so I don't understand why pandas doesn't behave the same way.
x = D.Decimal('1.0')
print(type(x))
結(jié)果:
`<class 'decimal.Decimal'>`
推薦答案
我覺得你需要轉(zhuǎn)換器:
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'>
這篇關(guān)于pandas read_csv 列 dtype 設(shè)置為十進制但轉(zhuǎn)換為字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!