How to Sort Pandas DataFrame with Examples

How to Sort Pandas DataFrame with Examples
How to Sort Pandas DataFrame with Examples

Sort Pandas DataFrame with Example’s

It’s very much easier to Sort Pandas DataFrame using the sort_values function from DataFrame class. In this tutorial, you are going to learn how to sort Pandas DataFrame with examples.

Let’s start with the sample DataFrame. Now assume you have the following data for sorting:

ModelBatteryPrice
Google Pixel 3291537300
Oneplus 7408553999
Asus ROG600045000
Oppo Reno406539990
Redmi K20400027244

Create a DataFrame using Python Program:

The output for the above program will be:

"How

Sorting Pandas DataFrame in Ascending Order

The sort_values() function sorts data in ascending order by default. In this example, we going to sort the Pandas DataFrame in ascending order by using Model .

The complete code to sort DataFrame in ascending order will look like:

The output of the above code will be:

"How

As you can see how the data is sorted in ascending order. The above output Asus ROG is in the first place while in Google Pixel 3 second place.

Sort Pandas DataFrame in Descending Order

In this example, we going to sort the Pandas DataFrame in descending order by using Model name. To sort in descending order you should add ascending parameter with value false as given below:

The complete code to sort DataFrame in ascending order will look like:

The output of the above code will be:

"How

As you can see how the data is sorted in descending order. The above output Redmi K20 is in the first place while Oppo Reno in second place.

Sorting Pandas DataFrame Based on Multiple Columns

In this example, we going to sort the Pandas DataFrame based on multiple columns by using Battery and Price. To sort DataFrame based on multiple columns you should set values as given below:

The complete code to sort DataFrame in ascending order will look like:

The output of the above code will be:

"How

As you can see how the data is sorted based on Battery and Price columns.

Conclusion

You have successfully learned How to Sort Pandas DataFrame with Examples. If you have any queries regarding this tutorial please don’t forget to comment below.

LEAVE A REPLY

Please enter your comment!
Please enter your name here