我正在尝试将字符串转换为浮点数,但是我得到了标题中的错误。我不明白为什么它不将句点(“.”)识别为十进制。这是我的数据帧的头部。
Country Variable \
0 Afghanistan Inflation, GDP deflator (annual %)
1 Afghanistan GDP (constant 2010 US$)
2 Afghanistan Population, total
3 Afghanistan Population ages 15-64, total
4 Afghanistan Employment to population ratio, 15+, total (%)...
2007 [YR2007] 2008 [YR2008] 2009 [YR2009] 2010 [YR2010] \
0 22.3820157780035 2.17910328500052 -2.10708255443797 9.43779477259656
1 11721187594.2052 12144482858.18 14697331940.6464 15936800636.2487
2 26616792 27294031 28004331 28803167
3 13293041 13602366 13950492 14372378
4 47.1220016479492 47.0480003356934 47.015998840332 47.0429992675781
以下是代码(使用Python 3.6):
growth_raw.iloc[:,3:] = growth_raw.iloc[:,3:].values.astype('float64')
I get:
ValueError: could not convert string to float: '.'
非常感谢您的帮助和建议。
更新:我不小心把NAs“..”转换成了“。”。现在我已经将它们转换为“”。我现在得到了。
ValueError: could not convert string to float:
我已经尝试过
growth_raw.apply(lambda x: x.str.strip())
对于转换,我尝试了
growth_raw.iloc[:,2:].values.astype(float)
这导致我出现了上述错误。我也尝试了以下两种方法,它们没有报错,但对数据没有任何影响:
growth_raw.iloc[:,2:].apply(lambda x: pd.to_numeric(x), axis=0)
growth_raw.iloc[:,2:].apply(pd.to_numeric,errors='coerce')
0.0
可以直接表示为.
。你希望如何处理这些数据呢? - undefinedpd.to_numeric
- undefined