简体   繁体   English

如何在我的数据帧中将字符串转换为浮点数? (蟒蛇)

[英]How to convert a string to a float in my dataframe? (Python)

I'm working with my dataframe in Python. 我正在用Python处理数据框。 Dataframe looks like this: 数据框如下所示:

Timestamp                  cpu_system           Host
 2018-01-09 20:03:22     1.3240749835968018     pwp2
 2017-09-30 21:03:22     2.0                    pwp2 
 ...................................................   

When I check on dtypes on this dataframe, I get this: 当我检查此数据帧上的dtypes时,得到以下信息:

   timestamp     object
   cpu_system    object
   host          object
 dtype: object

I want to change cpu_system into float. 我想将cpu_system更改为float。 Running this code: 运行此代码:

 df[['cpu_system']] = df[['cpu_system']].astype(float)

Getting this error: 收到此错误:

ValueError: could not convert string to float: value

How should I fix it? 我应该如何解决?

You can first check what values cannot be converted by: 您可以先检查哪些值不能通过以下方式转换:

print (df[pd.to_numeric(df['cpu_system'], errors='coerce').isnull()])

and then use to_numeric with parameter erors='coerce' for convert bad values to NaN : 然后用to_numeric与参数erors='coerce'坏值转换为NaN

df['cpu_system'] = pd.to_numeric(df['cpu_system'], errors='coerce')

And filter problematic values out if necessary by boolean indexing : 并在必要时通过boolean indexing过滤掉有问题的值:

df = df[df['cpu_system'].notnull()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM