rosefun
rosefun

Reputation: 1857

How to determine if a column contains certain elements in pandas

I want to check if the column app contains the element of myList.

import pandas as pd 
df=pd.DataFrame({'app':['a,b,c','e,f']})
myList=['b', 'f']
print(df)

Output:

     app
0  a,b,c
1    e,f

Expected:

     app  contains_b  contains_f
0  a,b,c          1           0
1    e,f          0           1

Upvotes: 1

Views: 83

Answers (1)

jezrael
jezrael

Reputation: 862641

Use str.get_dummies for all indicator columns and then filter them by reindex by list:

df = df.join(df['app'].str.get_dummies(',').reindex(columns=myList).add_prefix('contains_'))
print (df)
     app  contains_b  contains_f
0  a,b,c           1           0
1    e,f           0           1

Or use loop with str.contains and casting boolean mask to integers:

for c in myList:
    df[f'contains_{c}'] = df['app'].str.contains(c).astype(int)
print (df)
     app  contains_b  contains_f
0  a,b,c           1           0
1    e,f           0           1

Upvotes: 6

Related Questions