pandas版本0.13
d = {'one':['97628', '97628', '97628.271', '97628271'],
'two':['98800', '98800', '98800.000', '98800000']}
a = pd.DataFrame(d)
a
a.dtypes
一个对象
两个对象
dtype:object
到目前为止,一切看起来都很好。然后我尝试将字符串转换为浮点数。
a.loc[:,'one'] = a.loc[:,'one'].astype(float)
a.loc[:,'two'] = a.loc[:,'two'].astype(float)
执行代码后没有任何变化。
a.dtypes
一个对象
两个对象
dtype:object
最糟糕的是数据框中的数据已经改变
这是一个错误还是我错误地更改了数据类型?
答案 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