将带逗号的Pandas字符串列更改为浮点数

3

我运行了这段代码:

df["VotesPerYear"] = df["Votes"]/df["Years"]

并收到了以下错误消息:

"TypeError: unsupported operand type(s) for /: 'unicode' and 'float'"

df["Votes"]是一个用逗号作为千位分隔符的数字字符串。将其转换为浮点数以执行操作的最佳方法是什么?


1
你是怎么加载这些数据的?如果你使用了 read_csv,那么你可以让 pandas 把逗号视为千分位分隔符:read_csv(thousands=',') - EdChum
2个回答

7

您可以使用str.replace,替换为空,然后使用astype方法将列转换为浮点数:

df["VotesPerYear"] = df["Votes"].str.replace(",", "").astype(float) / df["Years"]

1
如果df['Votes']中的每个元素都是以u'x,xxx,xxx.xx'的形式表示的,我们可以这样做:
    df["VotesPerYear"] = df["Votes"].map(lambda x: float(''.join(x.split(',')))) / df["Years"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接