将值类型为字符串的列转换为数字

Convert column where values type are string to numeric

我有这个 DF (gdp_g20),其中包含 GDP 信息,第一行示例如下:

Country Name Country Code Indicator Name Indicator Code 2014
Argentina ARG GDP (current US$) NY.GDP.MKTP.CD 6,320,000,000.00

我想绘制它,但由于“2014”列的值类型是字符串,因此不可能。

所以有人知道如何将 gdp_g20['2014'] 转换为数字数据吗?我看过一些帖子,但其中 none 有效。

提前致谢。

我尝试去掉 $ 符号并用 to_numeric 转换,如下所示:

gdp_g20['2014'] = gdp_g20['2014'].apply(lambda x: x.replace('$', ''))
gdp_g20['2014'] = pd.to_numeric(gdp_g20['2014'])

但后来我得到了错误:

“无法解析位置 0 处的字符串“526,320,000,000.00””

您需要删除 $ 并删除 ,,这应该可以做到。

gdp_g20['2014'] = data['2014'].str[1:].str.replace(',','').astype(float)

看来您的方向是正确的,您只需要也删除“,”

像这样在你的代码中添加另一行是可行的

gdp_g20["2014"] = gdp_g20['2014'].apply(lambda x: x.replace('$', ''))
gdp_g20["2014"] = gdp_g20['2014'].apply(lambda x: x.replace(',', ''))
gdp_g20['2014'] = pd.to_numeric(gdp_g20['2014'])