将包含负字符串的pandas DataFrame列转换为float

时间:2015-10-22 18:01:30

标签: python-2.7 pandas

我有一个包含负字符串的pandas Dataframe df,我想将它们转换为float:

NY_resitor1  NY_resitor2    SF_type        SF_resitor2 
     45          "-36"          Resis          40                  
     47           "36"          curr           34                    
      .            .           .              .                   
     49           "39"          curr           39 
     45          "-11"          curr           12 
     12          "-200"          Resis          45

这是我写的代码

df["NY_resitor2 "]=df["NY_resitor2 "].astype(float)

但我有错误:

ValueError: could not convert string to float: "-32"

问题是什么?

1 个答案:

答案 0 :(得分:3)

我认为这可能是您的字符串数据中某处有"-"奇怪的unicode版本的情况。例如,这应该有效:

>>> import pandas as pd
>>> ser = pd.Series(['-36', '36'])
>>> ser.astype(float)
0   -36
1    36
dtype: float64

但事实并非如此,因为我已将标准减号替换为U+2212 minus sign

>>> ser2 = pd.Series(['−32', '36'])
>>> ser2.astype(float)
...
ValueError: could not convert string to float: '−32'

你可以通过使用str.replace()

专门删除有问题的字符来解决这个问题
>>> ser2.str.replace('−', '-').astype(float)
0   -32
1    36
dtype: float64

如果那不是问题,那么我不知道是什么!

编辑:另一种可能性是你的字符串可能在其中有引号。 e.g。

>>> ser3 = pd.Series(['"-36"', '"36"'])
>>> ser3.astype(float)
...
ValueError: could not convert string to float: '"-36"'

在这种情况下,您需要先将它们剥离出来:

>>> ser3.str.replace('"', '').astype(float)
0   -36
1    36
dtype: float64
相关问题