我运行了这段代码:
df["VotesPerYear"] = df["Votes"]/df["Years"]
并收到了以下错误消息:
"TypeError: unsupported operand type(s) for /: 'unicode' and 'float'"
df["Votes"]是一个用逗号作为千位分隔符的数字字符串。将其转换为浮点数以执行操作的最佳方法是什么?
我运行了这段代码:
df["VotesPerYear"] = df["Votes"]/df["Years"]
并收到了以下错误消息:
"TypeError: unsupported operand type(s) for /: 'unicode' and 'float'"
df["Votes"]是一个用逗号作为千位分隔符的数字字符串。将其转换为浮点数以执行操作的最佳方法是什么?
您可以使用str.replace
将,
替换为空,然后使用astype
方法将列转换为浮点数:
df["VotesPerYear"] = df["Votes"].str.replace(",", "").astype(float) / df["Years"]
df["VotesPerYear"] = df["Votes"].map(lambda x: float(''.join(x.split(',')))) / df["Years"]
read_csv
,那么你可以让 pandas 把逗号视为千分位分隔符:read_csv(thousands=',')
。 - EdChum