RogerKint
RogerKint

Reputation: 652

How to combine/reduce multiple rows from a dataframe that share the same ID based on a business rule?

I have a dataframe that looks like this:

   A  B  C.  ID  
0. 1. 0. 1.   1
1. 0. 0. 1.   2 
2. 1. 1  0.   1 
3. 0  1. 0.   3
.....

I want to reduce the dataframe so that only unique ID's remain. The business rule I want to apply is that if user n has multiple rows then they should be merged and the value 1 should take precedent over 0. So in the example dataframe, user with ID 1 has two rows (0 and 2). These should be reduced to

A B C
1 1 1

What would be the best way to go about doing this?

Upvotes: 0

Views: 27

Answers (1)

René
René

Reputation: 4827

pd.DataFrame(
    {
        'A': {0: 1, 1: 0, 2: 1, 3: 0},
        'B': {0: 0, 1: 0, 2: 1, 3: 1},
        'C': {0: 1, 1: 1, 2: 0, 3: 0},
        'ID': {0: 1, 1: 2, 2: 1, 3: 3}
    }
).groupby('ID').max()

Output:

    A  B  C
ID         
1   1  1  1
2   0  0  1
3   0  1  0

Upvotes: 1

Related Questions