if condition within groupby pandas

Viewed 57

Calculate the target column where default value is 1 but it is 0 when a group within ID1 has a Yes so for example in 9 there is one value as Yes we want to keep other No as 0
Given target col is expected answer

ID1 ID2 Match target
4   A10 Yes   1
4   A20 No    0
5   A30 Yes   1
6   A50 No    1
6   A60 No    1
7   A70 Yes   1
8   A60 No    1
9   A30 Yes   1
9   A20 No    0
9   A10 No    0
1 Answers

You can use Series.eq for compare with GroupBy.transform and GroupBy.all for test groups with only No value:

m1 = df['Match'].eq('No').groupby(df['ID1']).transform('all')
#or test not equal Yes
m1 = df['Match'].ne('Yes').groupby(df['ID1']).transform('all')
#alternative
#m1 = ~df['ID1'].isin(df.loc[df['Match'].ne('No'), 'ID1'])
m2 = df['Match'].eq('Yes')

df['target1'] = (m1 | m2).view('i1')
print (df)
   ID1  ID2 Match  target  target1
0    4  A10   Yes       1        1
1    4  A20    No       0        0
2    5  A30   Yes       1        1
3    6  A50    No       1        1
4    6  A60    No       1        1
5    7  A70   Yes       1        1
6    8  A60    No       1        1
7    9  A30   Yes       1        1
8    9  A20    No       0        0
9    9  A10    No       0        0
Related