无法将字符串转换为浮点数

时间:2014-01-21 23:07:06

标签: pandas type-conversion

pandas版本0.13

虚拟数据帧

d = {'one':['97628', '97628', '97628.271', '97628271'],  
     'two':['98800', '98800', '98800.000', '98800000']}

a = pd.DataFrame(d)  
a

enter image description here

a.dtypes

一个对象
两个对象
dtype:object

到目前为止,一切看起来都很好。然后我尝试将字符串转换为浮点数。

a.loc[:,'one'] = a.loc[:,'one'].astype(float)  
a.loc[:,'two'] = a.loc[:,'two'].astype(float)  

执行代码后没有任何变化。

a.dtypes

一个对象
两个对象
dtype:object

最糟糕的是数据框中的数据已经改变

enter image description here

这是一个错误还是我错误地更改了数据类型?

1 个答案:

答案 0 :(得分:5)

这里发生的事情是转换正确发生:

In [21]: a.loc[:,'one'].astype(float)
Out[21]: 
0       97628.000
1       97628.000
2       97628.271
3    97628271.000
Name: one, dtype: float64

已分配到对象列(您看到的格式只是数字格式 - 数字正确)。

一种很好的方法是使用convert_objects

In [11]: a.convert_objects(convert_numeric=True)
Out[11]: 
            one       two
0     97628.000     98800
1     97628.000     98800
2     97628.271     98800
3  97628271.000  98800000

[4 rows x 2 columns]

In [12]: a.convert_objects(convert_numeric=True).dtypes
Out[12]: 
one    float64
two    float64
dtype: object