【问题标题】:Replace string in column with other text用其他文本替换列中的字符串
【发布时间】:2021-11-20 22:28:12
【问题描述】:

这似乎是一个包含许多在线示例的基本问题,但由于某种原因它对我不起作用。

我正在尝试将“A”列中值为“基于设施的测试-OH”的任何单元格替换为值“基于设施的测试-OH”。如果您注意到,两者之间的唯一区别是单个“-”,但是出于我的目的,我不想在分隔符上使用拆分功能。只是想找到需要替换的值。

我尝试了以下代码,但没有一个有效。

第一种方法:

df = df.str.replace('Facility-based testing-OH','Facility based testing-OH')

第二种方法:

df['A'] = df['A'].str.replace(['Facility-based testing-OH'], "Facility based testing-OH"), inplace=True

第三种方法

df.loc[df['A'].isin(['Facility-based testing-OH'])] = 'Facility based testing-OH'

【问题讨论】:

    标签: python pandas string replace


    【解决方案1】:

    试试:

    df["A"] = df["A"].str.replace(
        "Facility-based testing-OH", "Facility based testing-OH", regex=False
    )
    print(df)
    

    打印:

                               A
    0  Facility based testing-OH
    1  Facility based testing-OH
    

    df 已使用:

                               A
    0  Facility-based testing-OH
    1  Facility based testing-OH
    

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多