🎉 AI Engineers: Aporia's 2024 Benchmark Report and mutiSLM has been released. View the report here>>

Aporia How to's

How to Sort a DataFrame by Two or More Columns?

1 min read
sort dataframe by multiple columns pandas pyspark

In this short how-to article, we will learn how to sort DataFrame rows by two or more columns. Rows are sorted by the values in the first column. In the case of equality, the values in the second column are checked, and so on.

sort dataframe by multiple columns pandas pyspark


The sort_values function is used for sorting DataFrame rows. To sort by multiple columns, column names are written in a list.

df = df.sort_values(by=["A","B"])

By default, the index of the rows prior to sorting are kept, which is not an ideal situation. We can change this behavior by using the ignore_index parameter.

df = df.sort_values(by=["A","B"], ignore_index=True)


The PySpark equivalent of the sort_values function is orderBy. In the case of sorting by multiple columns, we write the column names in a list.

df = df.orderBy(["Date","Team"])

This question is also being asked as:

  • Sort (order) DataFrame rows by multiple columns

People have also asked for:

Green Background

Control All your GenAI Apps in minutes