将带有逗号的Pandas字符串列更改为Float [英] Change Pandas String Column with commas into Float
本文介绍了将带有逗号的Pandas字符串列更改为Float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我运行了代码:
df["VotesPerYear"] = df["Votes"]/df["Years"]
并收到错误:
"TypeError: unsupported operand type(s) for /: 'unicode' and 'float'"
df [ Votes]是一串数字,逗号作为千位分隔符。将其转换为浮点数以便执行操作的最佳方法是什么?
df["Votes"] is a string of numbers with commas as thousand separators. What is the best way to convert it into a float so I can perform the operation?
推荐答案
您可以使用 str.replace
将,
更改为空,然后使用 astype
方法:
You could use str.replace
to change ,
to nothing and then convert column to float with astype
method:
df["VotesPerYear"] = df["Votes"].str.replace(",", "").astype(float) / df["Years"]
这篇关于将带有逗号的Pandas字符串列更改为Float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文