问题描述
我有一个包含负字符串的 Pandas Dataframe df,我想将它们转换为浮点:
NY_resitor1 NY_resitor2 SF_type SF_resitor245"-36" 抵抗 4047 36"当前 34....49 39"当前 3945"-11" 1212-200"抵抗45
这是我写的代码
df["NY_resitor2 "]=df["NY_resitor2 "].astype(float)
但我有错误:
ValueError: 无法将字符串转换为浮点数:-32"
有什么问题?
我认为这可能是在您的字符串数据中某处有一个奇怪的 "-"
Unicode 版本的情况.例如,这应该有效:
但这不是,因为我已经用 U+2212 减号:
>>>ser2 = pd.Series(['−32', '36'])>>>ser2.astype(浮动)...ValueError: 无法将字符串转换为浮点数:'−32'你可以通过使用 str.replace()
专门去除有问题的字符来解决这个问题:
如果这不是问题,那么我不知道是什么!
另一种可能性是您的字符串中可能有引号.例如
>>>ser3 = pd.Series(['"-36"', '"36"'])>>>ser3.astype(浮动)...ValueError: 无法将字符串转换为浮点数:'"-36"'在这种情况下,您需要先删除这些:
>>>ser3.str.replace('"', '').astype(float)0 -361 36数据类型:float64I have a pandas Dataframe df that contains negative strings and i would like to convert them to 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
This is the code I wrote
df["NY_resitor2 "]=df["NY_resitor2 "].astype(float)
but I have the error:
ValueError: could not convert string to float: "-32"
what is the problem?
I think this might be a case of having a strange unicode version of "-"
somewhere in your string data. For example, this should work:
>>> import pandas as pd
>>> ser = pd.Series(['-36', '36'])
>>> ser.astype(float)
0 -36
1 36
dtype: float64
But this doesn't, because I've replaced the standard minus sign with a U+2212 minus sign:
>>> ser2 = pd.Series(['−32', '36'])
>>> ser2.astype(float)
...
ValueError: could not convert string to float: '−32'
you could address this by specifically getting rid of the offending characters, using str.replace()
:
>>> ser2.str.replace('−', '-').astype(float)
0 -32
1 36
dtype: float64
If that's not the issue, then I don't know what is!
Edit: another possibility is that your strings could have quotes within them. e.g.
>>> ser3 = pd.Series(['"-36"', '"36"'])
>>> ser3.astype(float)
...
ValueError: could not convert string to float: '"-36"'
In this case, you need to strip these out first:
>>> ser3.str.replace('"', '').astype(float)
0 -36
1 36
dtype: float64
这篇关于将包含负字符串的 Pandas DataFrame 列转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!