Pandas str.contains 超过一个列表?

Unk*_*der 3 python dataframe python-3.x pandas

我使用类似以下内容来更新我的数据框

df.loc[(df['Message'].str.contains('hello', case=False)),'SomeSeries'] = 'SomeUpdate'
Run Code Online (Sandbox Code Playgroud)

'hello'但当我的系列包含or'bicycle'或等时,我可能想更新。'monday'显然,我可以迭代列表,但我想知道是否有办法在一行中做到这一点?我想要类似的东西

watchlist = ['hello','bicycle','monday']
df.loc[(df['Message'].str.contains(watchlist, case=False)),'SomeSeries'] = 'SomeUpdate'
Run Code Online (Sandbox Code Playgroud)

Vic*_*cky 5

你需要,

 df.loc[(df['Message'].str.contains('|'.join(watchlist), case=False)),'SomeSeries'] = 'SomeUpdate'
Run Code Online (Sandbox Code Playgroud)

  • 可能想要制作 `'|'.join(re.escape(w) for w in watchlist)` 以防监视列表包含正则表达式特殊字符并且应被视为文字。 (2认同)