Home > Blockchain >  For each unique value in pandas column, sort other columns
For each unique value in pandas column, sort other columns

Time:08-24

I have a pandas dataframe as follows.

id      name      order
104337  CCC       7.0
104337  BBB       8.0
104337  AAA       9.0
104341  EE        1.0
104341  DD        2.0

I would like to group it by id with reversing the order for each id as follows.

id      name.     order
104337  AAA        9.0
104337  BBB        8.0
104337  CCC        7.0                  
104341  DD         2.0
104341  EE         1.0

I have tried df.groupby('id').apply(f) but I am confused how to create f function for my desired output.

CodePudding user response:

Let's try

out = (df.groupby('id', as_index=False)
       .apply(lambda g: g.sort_values('order', ascending=False))
       .reset_index(drop=True))
print(out)

       id name  order
0  104337  AAA    9.0
1  104337  BBB    8.0
2  104337  CCC    7.0
3  104341   DD    2.0
4  104341   EE    1.0

CodePudding user response:

You can first do groupby.apply then do sort_values too.

df.groupby('id').apply(lambda x:x).sort_values('order', ascending=False)

       id name  order
2  104337  AAA    9.0
1  104337  BBB    8.0
0  104337  CCC    7.0
4  104341   DD    2.0
3  104341   EE    1.0

CodePudding user response:

I have solved it I think using the following code.

df.sort_values(['order'],ascending=False).groupby('id').apply(lambda x: x['name'])
  • Related