将字符串转换为DataFrame中的float [英] Converting strings to floats in a DataFrame

查看:349
本文介绍了将字符串转换为DataFrame中的float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将包含字符串和NaN值的DataFrame列转换为浮点型.还有另一列的值为字符串和浮点数;如何将整个列转换为浮点数.

How to covert a DataFrame column containing strings and NaN values to floats. And there is another column whose values are strings and floats; how to convert this entire column to floats.

推荐答案

注意::pd.convert_objects现在已被弃用.您应该按照其他说明使用pd.Series.astype(float)pd.to_numeric 答案.

NOTE: pd.convert_objects has now been deprecated. You should use pd.Series.astype(float) or pd.to_numeric as described in other answers.

在0.11中可用.强制转换(或设置为nan) 即使astype失败,它也将起作用.其也逐个系列 因此它不会转换为说完整的字符串列

This is available in 0.11. Forces conversion (or set's to nan) This will work even when astype will fail; its also series by series so it won't convert say a complete string column

In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))

In [11]: df
Out[11]: 
     A    B
0  1.0  1.0
1    1  foo

In [12]: df.dtypes
Out[12]: 
A    object
B    object
dtype: object

In [13]: df.convert_objects(convert_numeric=True)
Out[13]: 
   A   B
0  1   1
1  1 NaN

In [14]: df.convert_objects(convert_numeric=True).dtypes
Out[14]: 
A    float64
B    float64
dtype: object

这篇关于将字符串转换为DataFrame中的float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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