Python Pandas: Assign particular value of Group to All Entries of That Group in dataframe

I have a data frame with below columns, using which need to create new columns by grouping Name. Status should be updated as active to entire group if it is active for any one St.

data = {'Name':['Tom', 'Tom', 'krish', 'jack','jack','Nam','sue'],
        'St':['S-123', 'S-290', 'S-123', 'S-147','S-98','S-123','S-38'],
        'Status':['Inactive','active','active','inactive','active','Inactive','Inactive']}
  
df = pd.DataFrame(data)

The desired output is

    Name     St    Status New Status
0    Tom  S-123  Inactive     active
1    Tom  S-290    active     active
2  krish  S-123    active     active
3   jack  S-147  inactive     active
4   jack   S-98    active     active
5    Nam  S-123  Inactive   Inactive
6    sue   S-38  Inactive   Inactive

1 answer

  • answered 2021-04-08 04:21 Marco

    you don't need to group, in one line you could do it with

    df['New Status'] = df.apply(lambda row: "active" if any(df.query('Name == @row.Name').Status == 'active') else "inactive", axis=1)