Dmytro Filipenko
Dmytro Filipenko

Reputation: 941

Merge into list groupby in pandas

I have a such dataframe

    id  sid frame   type    
    1   10  15      person
    2   11  45      person  
    2   11  45      animal  
    3   13  75      person  
    4   14  45      person  

my goal is to transform this dataframe in this.

    id  sid frame   type    
    1   10  15      person
    2   11  45      [person, animal]    
    3   13  75      person  
    4   14  45      person

Im looking a for a way to merge type column in a row with the same id, sid, frame

Upvotes: 1

Views: 154

Answers (1)

jezrael
jezrael

Reputation: 862641

You can use groupby with list with condition:

df = (df.groupby(['id','sid','frame'])['type']
       .apply(lambda x: x.tolist() if len(x) > 1 else x.values[0])
       .reset_index())
print (df)
   id  sid  frame              type
0   1   10     15            person
1   2   11     45  [person, animal]
2   3   13     75            person
3   4   14     45            person

If all values should be lists:

df = (df.groupby(['id','sid','frame'])['type']
       .apply(list)
       .reset_index())
print (df)
   id  sid  frame              type
0   1   10     15          [person]
1   2   11     45  [person, animal]
2   3   13     75          [person]
3   4   14     45          [person]

Upvotes: 2

Related Questions