Home > database >  Sort series on index for the values that are equal
Sort series on index for the values that are equal

Time:07-04

I have a Pandas series here:

s1=pd.Series([23,23,21,21,25,25,25])

Now when i do s1.value_counts(), i get another series which is this image:

enter image description here

What i want to do is, get the indexes with duplicate values, sort them based on index and place them back to the series. In this case, the output would be:

enter image description here

I have tried putting it in a dictionary, flipping the values and then sorting the values. But is there a much more pandas efficient way to do this? Thank you in advance!

CodePudding user response:

Is this is what you are after?:

import pandas as pd
s1=pd.Series([23,23,21,21,25,25,25])
s1.value_counts().sort_index(ascending=True).sort_values(ascending=False)

CodePudding user response:

Not sure about "without disturbing the order of the rest of the list". Docs say that value_counts sorts from most common to least common, so you can recreate this order and sort indexes within each group. You can do it by treating index as another column and then sorting on two columns - counts and index. Like this

s1.value_counts().reset_index().\
  sort_values([0,'index'],ascending=[False,True]).\
  set_index('index')`
  • Related