我运行了代码:
df["VotesPerYear"] = df["Votes"]/df["Years"]
并收到错误:
"TypeError: unsupported operand type(s) for /: 'unicode' and 'float'"
df [" Votes"]是一串数字,逗号为千位分隔符。将它转换为浮点数的最佳方法是什么,以便我可以执行操作?
答案 0 :(得分:3)
您可以使用str.replace
将,
更改为空,然后使用astype
方法将列转换为浮点数:
df["VotesPerYear"] = df["Votes"].str.replace(",", "").astype(float) / df["Years"]
答案 1 :(得分:1)
如果df ['Votes']中的每个元素的格式为u'x,xxx,xxx.xx',例如, 我们可以做到:
df["VotesPerYear"] = df["Votes"].map(lambda x: float(''.join(x.split(',')))) / df["Years"]