Skip to content Skip to sidebar Skip to footer

Pandas Groupby And Sort Max Values

I am trying to groupby two Columns in a pandas df and return the max value. I'm then hoping to sort these max values in relation to the same Columns. This is my attempt: import pa

Solution 1:

So you need groupby with transformsort_values

df.groupby('year').transform(pd.Series.sort_values,ascending=False)Out[42]:yearVal2014  C6T2V12015  D6T4U22016  A5B4D3S2T1Name:Num,dtype:int64

Solution 2:

use transform to sort the values returned by max

 data = ({
 'year' :      ['2016','2016','2016','2016','2016','2015','2015','2015','2015','2014','2014','2014','2014'],        
     'Val' : ['A','B','D','T','S','D','T','T','U','T','T','V','C'],                 
     'Num' : [1,2,4,5,3,6,4,3,2,5,6,1,2],                                     
     })

 df = pd.DataFrame(data = data)

 grouped = df.groupby(['year','Val']).max()
 print(grouped)
 print(grouped.transform(pd.Series.sort_values,ascending=False))

output:

 Num
      year Val     
      2014 C      2T6
           V      12015 D      6T4
           U      22016 A      1
           B      2
           D      4
           S      3T5

output 2:

NumyearVal2015 D62014 T62016 T5D42015 T42016 S3B22015 U22014 C22016 A12014 V1

Post a Comment for "Pandas Groupby And Sort Max Values"