Flag if there was an occurrence of a value in another column of pandas dataframe?

Viewed 31

I have the following dataframe:

import pandas as pd
df = pd.DataFrame({'a': ['x', 'x', 'y','w', 'x', 'z', 'z', 'y', 'w'],
                  'Flag': [1, 0, 0, 0, 1, 0, 0, 0, 1]})

I want to add a column b that will flag if any entry of a has a flag of 1 or not:

a Flag b
x 1    1
x 0    1
y 0    0
w 0    1
x 1    1 
z 0    0
z 0    0
y 0    0
w 1    1

What I did is: groupby a, cumsum Flag, every entry that > 0 will get 1, 0 otherwise. Is there any simpler method or function to do this?

1 Answers

You could do it with isin and .astype(int):

df['b'] = df['a'].isin(df.loc[df['Flag'].eq(1), 'a']).astype(int)
>>> df

   a  Flag  b
0  x     1  1
1  x     0  1
2  y     0  0
3  w     0  1
4  x     1  1
5  z     0  0
6  z     0  0
7  y     0  0
8  w     1  1
>>> 

Or for other situations, you might need np.where:

df['b'] = np.where(df['a'].isin(df.loc[df['Flag'].eq(1), 'a']), 1, 0)
Related