【问题标题】:Python string.replace() not replacing specified character stringPython string.replace() 不替换指定的字符串
【发布时间】:2021-05-20 06:32:51
【问题描述】:

我有一个包含“Search_Term”字段的数据框。一些搜索词包含我想删除的“AND”运算符,例如

df_concat.Search_Term.unique() 

返回:

Out[38]: array(['alcohol illness', 'alcohol fatality', 'alcohol cirrhosis', 'alcohol death',
       'alcohol poison', 'alcohol AND illness', 'alcohol AND cirrhosis'],
      dtype=object)

所以我尝试使用 string.replace() 删除它们:

df_concat["Search_Term"] = df_concat["Search_Term"].replace(" AND ", " ")

df_concat.Search_Term.unique() 

但我仍然得到:

Out[39]: array(['alcohol illness', 'alcohol fatality', 'alcohol cirrhosis', 'alcohol death',
       'alcohol poison', 'alcohol AND illness', 'alcohol AND cirrhosis'],
      dtype=object)

为什么在这种情况下 string.replace() 没有像我期望的那样运行?我已经查看了以前的问题,但我读过的问题似乎都没有在这种情况下提供解决方案。

【问题讨论】:

  • 你可以试试这个,让我知道结果df_concat["Search_Term"] = df_concat["Search_Term"].astype(str).replace(" AND ", " ")df_concat["Search_Term"] = df_concat["Search_Term"].str.replace(" AND ", " ")
  • 谢谢,这似乎有效!

标签: python arrays string replace


【解决方案1】:

正如 Preetham 上面建议的那样,我需要先转换为字符串(即使用 .str.replace() 而不仅仅是 .replace())

df_concat["Search_Term"] = df_concat["Search_Term"].str.replace(" AND ", " ")

df_concat.Search_Term.unique() 

给予:

Out[38]: array(['alcohol illness', 'alcohol fatality', 'alcohol cirrhosis', 'alcohol death', 'alcohol poison'],
      dtype=object)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 2015-08-05
    • 2012-06-23
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多