【问题标题】:Change Pandas String Column with commas into Float将带有逗号的 Pandas 字符串列更改为浮点数
【发布时间】:2016-03-31 10:54:24
【问题描述】:

我运行了代码:

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

并收到错误:

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

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

【问题讨论】:

  • 您是如何加载这些数据的?如果您使用了read_csv,那么您可以告诉 pandas 将逗号视为千位分隔符:read_csv(thousands=',')

标签: python-2.7 pandas dataframe typeerror


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果 df['Votes'] 中的每个元素都是 u'x,xxx,xxx.xx' 的形式,例如, 我们可以这样做:

        df["VotesPerYear"] = df["Votes"].map(lambda x: float(''.join(x.split(',')))) / df["Years"]
    

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 2020-02-08
      相关资源
      最近更新 更多