Home > Net >  Pandas: New Column, Assign whole group based on a row
Pandas: New Column, Assign whole group based on a row

Time:02-26

What is a way to add a Pandas column based on a condition "Has Covid", for the whole group "Class" in our example below? i.e. I want the "Email Alert" column, given Class, Student, and Has Covid column.

(i have searched quite a few posts but nothing seem to be applicable... i was thinking of adding a dictionary of class and do a map, but that seems inefficient)

Thanks in advance, N

enter image description here

CodePudding user response:

here is one way :

df['Email Alert'] = df.groupby('class')['hasCovid'].transform('max')

CodePudding user response:

You can do isin

df['classCovid'] = df['class'].isin(df.loc[df['Has Covid']==1,'class']).astype(int)
  • Related