【发布时间】:2017-10-24 03:53:25
【问题描述】:
我正在尝试将字符串转换为浮点数,但标题中出现错误。我不明白为什么它不将句点('.')识别为小数。这是我的数据框的头部。
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')
我明白了:
ValueError: could not convert string to float: '.'
任何明智的想法都值得赞赏。非常感谢。
更新:我不小心将 NA '..' 转换为 '.'。我现在已将它们转换为''。我现在明白了
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可能只表示为.。你想如何处理这些数据? -
使用
pd.to_numeric -
谢谢大家。两个都试过了。我已经更新了我原来的帖子。
-
想不通,但用 R 没问题:growth_raw[,3:11] = lapply(growth_raw[,3:11], as.numeric)
标签: python python-3.x pandas