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:
JavaScript
x
9
1
group condition final_condition
2
0 1 False False
3
1 1 False False
4
2 1 True False
5
3 2 True True
6
4 2 True True
7
5 3 True False
8
6 3 False False
9
I have tried many different things but can’t find a solution, so any help is appreciated.
Advertisement
Answer
use groupby()
+transform()
:
JavaScript
1
2
1
df['final_condition']=df.groupby('group')['condition'].transform('all')
2
output of df
:
JavaScript
1
9
1
group condition final_condition
2
0 1 False False
3
1 1 False False
4
2 1 True False
5
3 2 True True
6
4 2 True True
7
5 3 True False
8
6 3 False False
9