python-2.7 - 将带有逗号的 Pandas 字符串列更改为 Float

标签 python-2.7 pandas dataframe typeerror

我运行了代码:

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

并收到错误:

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

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

最佳答案

您可以使用 str.replace, 更改为空,然后使用 astype 将列转换为 float 方法:

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

关于python-2.7 - 将带有逗号的 Pandas 字符串列更改为 Float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34462207/

相关文章:

用于读取 SAS .xpt 文件的 pandas.read_sas() 不适用于存储在 Google Cloud Storage (GCS) 中的文件

python - 将微秒格式化为小数点后两位(实际上是将微秒转换为几十微秒)

python-2.7 - python : How to Modify metadata of Microsoft Office files?

python - 在 python 中从 Dataframe 构建 3d 矩阵

python - 如何在 Pandas 数据框列中选择一系列值?

python - 如何迭代 pandas 数据帧的每一行,然后有条件地在该行中设置新值?

python - 将单索引数据框添加到多索引数据框、Pandas、Python

python - 如何计算 pandas Dataframe 中分类数据的子组?

python - ImportError - 将 Falcon 应用程序部署到 AWS Elastic Beanstalk

python-2.7 - 加载 lightgbm 模型并使用 predict 与并行 for 循环卡住(Python)