How to sort DataFrame by column in Pandas

Read Time:9 Minute, 35 Second

Table of Contents

The ability to sort datasets is one of Pandas’ most appealing features. By sorting, you can see your relevant data at your table’s top (or bottom). There isn’t much you need to know right away. When you sort several columns with sort keys, the magic happens.

Sorting pandas by column are where the rows in the DataFrame are arranged in ascending or descending order using DataFrame by column value.

Sort DataFrame by column in Pandas

To sort a DataFrame by column values, use pandas.DataFrame.sort_values(). The syntax for sorting pandas by column is as follows:

Essentially, sorting pandas by column values, use pandas.DataFrame.sort_values(columns, ascending=True) with a list of column names to sort by as columns and either True or False as ascending.

While sorting with sort values() is simple in theory, you may have issues with missing values or custom labels in practice (for example, H, L, M for High, Low, and Medium). The initial results of print(df) are:


The example above sorts by column “A” in ascending order.

The example shown above sorts the column “B” in descending order.

Sorting Pandas

Let’s look at the many parameters you can send to pd.

by – You can sort by a single name or a list of names. It could be the names of columns or indexes. When you want to sort by multiple columns, pass a list of names.

It is the axis that will be ordered. You must specify whether Pandas you want the rows to be sorted (axis=’index’ or 0)? Do you want to sort the columns (axis=’columns’ or 1)?


ascending (Default: True) – If you’re sorting by multiple columns, you can pass a single boolean (True or False) or a list of booleans ([True, False]).

inplace (Default: False)

If true, your new sort order will overwrite your current DataFrame. It will alter the situation. Your DataFrame will be returned to you if false. When working with the DataFrame later in the code, we usually use inplace=True. However, if we’re visually looking at the sort order, we’ll use inplace=False.

type (defaults to ‘quicksort’)

Select the sorting algorithm you want to use. Unless you’re dealing with massive databases, this won’t matter much. Even then, you’d have to understand the distinctions and drawbacks.


na_position (Default: ‘last’)

You may tell pandas where you want your NAs to go (if you have them). At the beginning (‘first’) or the end (‘last’).

ignore_index (Default: False)

If false, your index values will change as the sorting progresses. It is beneficial when you want to check how the rows have shifted around. Set ignore_index=True if you wish your index to stay in order and remain at 0, 1, 2, 3,…, n-1.

Returns: DataFrame or None


DataFrame with sorted values or None if inplace=True.

Key: callable, optional
The latter is an incredible parameter! You can supply a function to the key that will produce a derived value that will be the key that is sorted on, based on your column or row. Before sorting, apply the key function to the values. It is comparable to the built-in sorted() method’s key parameter, except that you should vectorize this critical function. It should expect and deliver a Series with the same shape as the input. It will apply separately to each column in the table.

Take a look at the sample below.

Let’s say you wanted to sort by a column’s absolute value. You could sort by creating a derived column with fundamental values, but it feels inconvenient. Instead, use a pivotal function to sort your column by absolute values.

Let’s start by making a dataframe.


Ascending vs. Descending Pandas

You’ll need to decide whether you want your values sorted from highest to lowest (descending) or from lowest to highest (ascending).

  • Ascending = The lowest values will appear first or at the top.
  • Ascending = The higher values will appear first or on top.

A Jupyter notebook demonstrates the various ways to sort a pandas DataFrame can be found here.

Values Sorted by Pandas

Sort Values allows you to sort a DataFrame (or series) by a column or row. Consider the following examples:

  • Sort DataFrame by a single column
  • Sort DataFrame by mulitple columns
  • Sort DataFrame by a single row
  • Apply a key to sort on – Example: Sort by absolute value

Let’s start by making our DataFrame of city temperatures.

city temperatures dataframe

Sorting a DataFrame by a single column

You have to call YourDataFrame to sort a dataframe by a single column.


Let’s sort our DataFrame by temperatures in Chicago in this case.

sort city temperatures dataframe by Chicago
sort city temperatures dataframe by Chicago

It’s worth noting how the DataFrame was ordered from lowest to highest by the Chicago column. Because ascending=True is the default sort order, this is the case. Set ascending=False if you wish to reverse the order.

sort city temperatures dataframe by Chicago descending
sort city temperatures dataframe by Chicago descending

Sorting DataFrame by numerous columns

We’re going to make another DataFrame that will work better for sorting by several columns.

Assume we wanted to arrange ‘Type’ alphabetically (such that Bar is above the Restaurant) before sorting AvgBill in decreasing order (highest > lowest). We’ll need to do the following to accomplish this.

Use the “by=” argument to specify a list of column names. The “ascending” parameter takes a list of booleans that informs pandas which columns we want ascending or descending.


sort by type and AvgBill
sort by type and AvgBill

Notice how we sorted the first column, ‘Type,’ ascending=True, then ascending=False for the second column, ‘AvgBill.’

Sorting the DataFrame by a single row

Let’s move on to the row side now. We only want to sort my columns in a precise order on rare occasions (we prefer tall tables to wide tables, so this doesn’t happen often). Further, we need to inform Pandas that I want to sort by rows and which row I want to sort by to accomplish this. Let’s go back to the DataFrame we started with. We’re going to sort by the label index=3. So, we’ll need to set axis=1 to accomplish this.

Our DataFrame’s columns have now been sorted in ascending order by index=3!

Special Key Sorting the Columns

We wish to sort the column by the absolute worth of its contents in this situation. Check out Fairbanks; currently, -10 is the lowest value, but we’ll order by absolute value such that five is at the top.

What’s going on under the hood?


Pandas apply a function to each column value (much like pandas does). The object (or key) that is sorted on will be the outcome of that function.

Now, look at how we sorted on Fairbanks, with the lowest numbers at the top (descending) and the value 5 being higher than the value -10. It is because we specified the key as the column’s absolute value!

If you’re utilizing numerous columns, you won’t be able to call multiple vital functions. You’ll need to use the same process to sort all the columns.

How to handle Missing Values when Sorting

Because missing values or NaN are not comparable to other values, sort_values() default to sorting the NaN at the end of the DataFrame and modifying an existing DataFrame to add NaN and sorting on the age column, for example.

Sorting Pandas Data frame by placing the missing values first

Sorting Pandas Data frame by placing the missing values first
Sorting Pandas Data frame by placing the missing values first

Example: Sorting Pandas Data frame by placing the missing values first


Example: Sorting Pandas Data frame by placing the missing values first
Example: Sorting Pandas Data frame by placing the missing values first

Natural sort with the critical argument, using the natsort

Natural sort with the critical argument, using the natsort
Natural sort with the critical argument, using the natsort

Modifying Your DataFrame Using Sort Methods

Both.sort_values() and.sort_index() have yielded DataFrame objects in all of the instances you’ve seen thus far. It is the case because sorting in pandas does not operate in place by default. Because it creates a new DataFrame instead of changing the original, this is the most popular and preferred technique to examine data with pandas. It allows you to keep the data in the same state as read from the file.

However, you can directly edit the original DataFrame by setting the optional argument inplace to True. The inplace parameter is present in the majority of pandas methods. In the examples below, you’ll learn how to use inplace=True to sort your DataFrame.

In-place use of.sort_values()

When inplace is set to True, the original DataFrame is modified so that the sort methods return None. Sort your DataFrame by the values of the city08 column. But with inplace set to True, as in the first example:

.sort_values() does not return a DataFrame, as you can see. It is how the original df looks. The data in the df object are now sorted in ascending order by the city08 column. Your original DataFrame has been altered, and the changes will remain in place. Because you can’t undo the changes to your DataFrame, it’s best to avoid using inplace=True for analysis.


In-Place use of .sort_index()

The following example shows how to use inplace with .sort_index(). Because the index is constructed in ascending order when you read your file into a DataFrame, you can change the order of your df object again. To change the DataFrame, use.sort _ndex() with inplace set to True:

.sort_index() has now been used to modify your DataFrame once more. Because your DataFrame still has its default index, sorting it in ascending order restores the original order of the data.

If you’re familiar with Python’s built-in functions sort() and sorted(), you’ll recognize the inplace parameter in the pandas’ sort methods. Check out How to Use sorted() and sort() in Python for additional information.


This article covered all possibilities for using Python’s sort_values() to sort a DataFrame in Pandas. Sorting a DataFrame in Pandas in a given order, such as ascending or descending, is very easy with the built-in method sort)values()!

You now know how to utilize the pandas library’s.sort_values() and.sort_index() methods (). You can use a DataFrame to perform fundamental data analysis with this understanding. While there are many similarities between these two methodologies, understanding the differences allows you to choose which one to utilize for various analytical tasks.


These techniques are an essential aspect of mastering data analysis. They’ll assist you in laying a solid foundation for doing more sophisticated pandas operations. The pandas manual is an excellent resource if you want to see some examples of more advanced uses of pandas sort methods.

You can give these a shot and tell us what other techniques you use to sort your Pandas DataFrame.


CyberSEO Pro - OpenAI GPT-3 autoblogging and content curation plugin for WordPress