【问题标题】:Replacing values using dictionary使用字典替换值
【发布时间】:2021-02-12 21:28:06
【问题描述】:

正则表达式替换不起作用的原因是什么?我已尝试确保没有多余的空间。

df.column
0    Test_With_Him
1    And_another option with him
2    and_another reason with her

replacement = {'_':' ',Test With': 'test with', 'and another': 'And another& AND'}
df['column'] = df.column.replace('\s+',' ' , regex=True).str.strip().replace(replacement, regex=True)

当我做df.loc[df['column']=="and another reason with her"] 时,什么都没有改变。

【问题讨论】:

  • 你没有把结果赋值回去,df.column = df.column....
  • 我是在原始代码中完成的,但忘记在此处输入,抱歉。还是不行
  • 无法复制,我得到的是And another& AND reason with her 而不是and another reason with her
  • 你知道它失败的任何原因吗?

标签: python python-3.x regex pandas


【解决方案1】:

请使用df.replace(regex=dict)

df=pd.DataFrame({'test':["Test With Him","And Another option with him",'and another reason with her']})

replacement = {r'Test With': 'test with', r'And Another': 'And another& AND'}

df=df.replace(regex=replacement)

                        test
0                     test with Him
1  And another& AND option with him
2       and another reason with her

【讨论】:

  • 它应该可以工作。为我工作。你用的是什么版本?为什么不起作用?错误?
  • 它替换了字典中的一些项目,但不是所有项目。我不明白为什么。
  • 修改您的问题并显示未更改的内容,我们可以尝试提供帮助。也许是空白或案例问题
  • df=df.replace(replacement,regex=True)
  • Yh 已排序,这是因为我在字典中有一个项目将下划线替换为空格。我认为这意味着字典中的其余项目可能没有下划线,因为下划线替换是字典中的第一项。感谢您的帮助