【发布时间】:2020-07-16 19:49:35
【问题描述】:
我有以下列表和数据框:
mylist = ['foo', 'bar', 'baz']
df = pd.DataFrame({'Col1': ['fooThese', 'barWords', 'baz are', 'FOO: not', 'bAr:- needed'],
'Col2': ['Baz:Neither', 'Foo Are', 'barThese', np.nan, 'but this is fine']})
如果在 DataFrame 中找到字符串,我想替换 mylist 中的字符串。 我可以使用以下正则表达式模式替换一些:
pat = '|'.join([r'\b{}'.format(w) for w in mylist])
df2 = df.replace(pat, '', regex=True)
但是,这并没有放置所有实例。我想要的输出如下:
Col1 Col2
0 These Neither
1 Words Are
2 are These
3 not NaN
4 needed but this is fine
【问题讨论】:
-
当心这种情况:
Baz!=baz在您的代码中。
标签: python regex pandas replace re