Skip to content
Advertisement

Change all values in column if a condition is met within a group in Pandas dataframe

I have a dataframe that contains many rows, and a condition that is checked for each row and saved as a boolean in a column named condition. If this condition is False for any row within a group, I want to create a new column that is set to False for the whole group, and to True if the condition for every row within the group is set to True.

The final dataframe should look like this:

       group  condition  final_condition
0      1      False            False
1      1      False            False
2      1       True            False
3      2       True             True
4      2       True             True
5      3       True            False
6      3      False            False

I have tried many different things but can’t find a solution, so any help is appreciated.

Advertisement

Answer

use groupby()+transform():

df['final_condition']=df.groupby('group')['condition'].transform('all')

output of df:

group   condition   final_condition
0   1   False       False
1   1   False       False
2   1   True        False
3   2   True        True
4   2   True        True
5   3   True        False
6   3   False       False
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement