How to Sort a Pandas Dataframe Object By a Column in Python



Python


In this article, we show how to sort a pandas dataframe object by a certain column.

Let's say you have a pandas dataframe object and they have the columns: total_bill, tip, sex, smoker, day, time, and size.

Let's say that you want to sort the dataframe by the total_bill.

This can be done with the pandas sort_values() function.

Inside of this sort_values() function, you place the name of the column that you want to sort the pandas dataframe object according to.

So, as an example, I will use the tips pandas dataframe object. This contains the columns: total_bill, tip, sex, smoker, day, time, and size.

To do this, the following code is used shown below.



So let's go over the code now.

So the first thing is we import seaborn, because we want to use the tips datasheet that seaborn provides.

We then load in the tips data using the sns.load_dataset('tips'). We set this equal to the variable, df, standing for dataframe.

We then take this df variable and we use the sort_values() function in order to sort the dataframe object according to the total_bill column. You can see that the dataframe object is now sorted by the total_bill column. The values for this are in order for least to greatest. You can see that the lowest total_bill is 3.07 and the highest is 50.81.

As another example, we will sort the dataframe object now according to the tip column.

This is shown in the following code below.



So we've now sorted the pandas dataframe object according to the tip column.

So the sort_values() function is a powerful function in pandas that allows us to sort a pandas dataframe object according to any column of a dataframe in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...