【问题标题】:Why does .replace not work in my dataframe? [duplicate]为什么 .replace 在我的数据框中不起作用? [复制]
【发布时间】:2022-01-17 10:47:11
【问题描述】:

我的代码大致是这样的:

df[['floatcol1', 'floatcol2', 'floatcol3']] = df[['floatcol1', 'floatcol2', 'floatcol3']].astype(str)

df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']] = df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']].replace(',', '.')

但它仍在打印我的值,例如 527,1 和 847,9,而不是我想要的 527.2 和 847.9。我很困惑为什么 replace 不能替换逗号。

【问题讨论】:

  • 缺少regex=True -> .replace(',', '.', regex=True)
  • @HenryEcker 不,这不是问题。如要求的那样,我们想替换文字逗号。
  • 我不明白 @KarlKnechtel 没有 regex=True replace 只会交换完全匹配的字符串。 只包含一个逗号的单元格。看来我们想在字符串中用点替换逗号。
  • OP:你期望.astype(str)结果包含逗号吗?或者您是否正在尝试修复错误的本地化设置?或者只是什么?
  • 这毫无意义@KarlKnechtel 没有regex=True 它只会替换完全匹配的字符串。 仅包含一个逗号的单元格将被替换。使用regex=True,它将单元格中包含的逗号替换为其他文本。这是在 DataFrame 级别解决此问题的标准方法。

标签: python pandas


【解决方案1】:

试试

df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']].replace({',':'.'}, regex=True, inplace=True)

【讨论】:

    【解决方案2】:

    我明白了。你必须使用:

    df['col'] = df['col'].str.replace(',', '.', regex=True).astype(float)
    

    对于每一列。如果传入列列表,Python 无法将列表转换为字符串。可能有更简单、更有效的方法,但我只有三列要转换。

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 2019-08-29
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2018-12-13
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多