Python 使用字典替换值
regex replacment不起作用的原因是什么?我已尝试确保没有多余的空间Python 使用字典替换值,python,python-3.x,regex,pandas,Python,Python 3.x,Regex,Pandas,regex replacment不起作用的原因是什么?我已尝试确保没有多余的空间 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.r
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']==”和另一个原因“]时,没有任何变化。请使用
df.replace(regex=dict)
您没有将结果分配回,
df.column=df.column….
我在原始代码中分配了结果,但忘记在此处键入,抱歉。它仍然不起作用。无法重新编程,我得到了和另一个与她
有关的理由,而不是和与她
有关的另一个理由。你知道它可能失败的原因吗?不幸的是,这仍然不起作用。它应该起作用。为我工作,你在哪个版本?为什么不工作?错误?它替换字典中的某些项,但不是所有项。我不明白为什么。df=df.replace(replacement,regex=True)
Yh排序,因为我在字典中有一个项目用空格替换了下划线。我认为这意味着字典中的其他条目可能没有下划线,因为下划线替换是字典中的第一个条目。谢谢你的帮助
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