用逗号将Pandas字符串列更改为Float

时间:2015-12-25 10:52:45

标签: python-2.7 pandas dataframe typeerror

我运行了代码:

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

并收到错误:

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

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

2 个答案:

答案 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"]
相关问题