且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:在多列中查找字符串,然后在新列中返回

更新时间:2022-06-15 22:00:46

以下是使用 str.contains

Here is a way using stack and str.contains with df.where:

cols = ['col1', 'col2', 'col3', 'col4']
df['b'] = (df[cols].where(df[cols].stack().str.contains('b')
         .unstack(fill_value=False)).ffill(1).iloc[:,-1])


print(df)

   ID  col0 col1 col2 col3 col4  col5    b
0   1  jack  a/h  t/m  w/n  y/h    56  NaN
1   2   sam  z/n  b/w  NaN  NaN    93  b/w
2   3  john  b/i  y/d  p/d  NaN    33  b/i