I have the following dataframe:
import pandas as pd
df = pd.DataFrame({'a': ['1', '1', '1', '2', '2', '2', '3', '3', '4', '4'], 'b': ['True', 'False', 'True', 'True', 'True', 'True', 'True', 'True', 'False', 'False']})
a b
0 1 True
1 1 False
2 1 True
3 2 True
4 2 True
5 2 True
6 3 True
7 3 True
8 4 False
9 4 False
I want to combine all numbers in column a with the same numbers. Moreover, I want to state in column b , if all values of b are true for a specific a to set it true or if at least one is false to set it false.
The result should therefore look like this:
a b
0 1 False
1 2 True
2 3 True
3 4 False
How do I achieve this? I tried it with groupby, but I'm not able to find a suitable solution.
Use GroupBy.all
for test if all values are True
s:
#if necessary convert strings to boolean
df['b'] = df['b'].map({'True':True, 'False':False})
df = df.groupby('a', as_index=False)['b'].all()
print (df)
a b
0 1 False
1 2 True
2 3 True
3 4 False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.