How to Sort a Series in Pandas

Updated: March 11, 2023 By: Khue Post a comment

To sort a given Series in Pandas, you can use the sort_values() method. By default, the method sorts in ascending order, but you can choose descending order by passing the ascending=False argument. For more clarity, see the examples below.


Sorting a Series of numbers

Suppose you have a Series of random integers:

import pandas as pd
import numpy as np

s = pd.Series(np.random.randint(0, 10, 5))

To sort the Series in ascending order, you can call the sort_values() method without any arguments:

s_sorted = s.sort_values()


[0 1 1 5 8]

Sorting a Series contains object data type

Sorting a Series that contains object data type is similar to sorting a Series that contains numeric data type.


import pandas as pd

# create a Series of strings
s = pd.Series(['apple', 'banana', 'cherry', 'durian'])

# sort the Series in descending order
s_sorted = s.sort_values(ascending=False)


3    durian
2    cherry
1    banana
0     apple
dtype: object

Since the data type of the Series is object, the method sorted the strings in lexicographic order.