Sling Academy
Home/Pandas/How to Sort a Series in Pandas

How to Sort a Series in Pandas

Last updated: March 11, 2023

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.

Examples

Sorting a Series of numbers

Suppose you have a Series of random integers:

import pandas as pd
import numpy as np

np.random.seed(999)
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()
print(s_sorted.values)

Output:

[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.

Example:

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)
print(s_sorted)

Output:

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.

Next Article: Pandas Series: Counting NaN and Non-NaN Values

Previous Article: How to Create a Series in Pandas (with 6 Examples)

Series: Pandas Series: From Basic to Advanced

Pandas

You May Also Like

  • How to Use Pandas Profiling for Data Analysis (4 examples)
  • How to Handle Large Datasets with Pandas and Dask (4 examples)
  • Pandas – Using DataFrame.pivot() method (3 examples)
  • Pandas: How to ‘FULL JOIN’ 2 DataFrames (3 examples)
  • Pandas: Select columns whose names start/end with a specific string (4 examples)
  • 3 ways to turn off future warnings in Pandas
  • How to Integrate Pandas with Apache Spark
  • How to Use Pandas for Web Scraping and Saving Data (2 examples)
  • How to Clean and Preprocess Text Data with Pandas (3 examples)
  • Pandas – Using Series.replace() method (3 examples)
  • Pandas json_normalize() function: Explained with examples
  • Pandas: Reading CSV and Excel files from AWS S3 (4 examples)
  • Using pandas.Series.rank() method (4 examples)
  • Pandas: Dropping columns whose names contain a specific string (4 examples)
  • Pandas: How to print a DataFrame without index (3 ways)
  • Fixing Pandas NameError: name ‘df’ is not defined
  • Pandas – Using DataFrame idxmax() and idxmin() methods (4 examples)
  • Pandas FutureWarning: ‘M’ is deprecated and will be removed in a future version, please use ‘ME’ instead
  • Pandas: Checking equality of 2 DataFrames (element-wise)