Home > Net >  Sort pandas Series both on values and index
Sort pandas Series both on values and index

Time:05-27

I want to sort a Series in descending by value but also I need to respect the alphabetical order of the index. Suppose the Series is like this:

(index)
a         2
b         5
d         3
z         1
t         1
g         2
n         3
l         6
f         6
f         7

I need to convert it to the following Series without converting to DataFrame and then convert it to Series,

out:

(index)
f         7
f         6
l         6
b         5
d         3
n         3
a         2
g         2
t         1
z         1

I used lexsort but It wasn't suitable. It sorts both the value and index in ascending.

CodePudding user response:

You can first sort the index, then sort the values with a stable algorithm:

s.sort_index().sort_values(ascending=False, kind='stable')

output:

f    7
l    6
b    5
d    3
n    3
a    2
g    2
t    1
z    1
dtype: int64

used input:

s = pd.Series({'a': 2, 'b': 5, 'd': 3, 'z': 1, 't': 1, 'g': 2, 'n': 3, 'l': 6, 'f': 7})

CodePudding user response:

Series.sort_values(axis=0, ascending=False)

Can you try if this works given the information you have provided.

CodePudding user response:

Finally, I find the code solution:

y = s.nlargest(n) 

n: the number of the largest values to return.

  • Related