pandas read_csv column dtype设置为decimal,但转换为字符串 [英] pandas read_csv column dtype is set to decimal but converts to string

查看:4427
本文介绍了pandas read_csv column dtype设置为decimal,但转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pandas(v0.18.1)从名为'test.csv'的文件中导入以下数据:

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设置为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))

结果:

`<class 'int'> <class 'float'> <class 'str'> <class 'str'>`



我还尝试在导入后显式转换为十进制,运气(转换为浮动而不是小数)。

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))

结果:

`<class 'int'> <class 'float'> <class 'float'> <class 'str'>`

以下代码将'str'转换为'十进制,所以我不明白为什么熊猫的行为不一样。

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))

结果:

`<class 'decimal.Decimal'>`


推荐答案

我认为你需要转换器:

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'>

这篇关于pandas read_csv column dtype设置为decimal,但转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆