Pandas Sort by Column : How to do it using the Best Examples

Pandas Sort by Column Featured Image

Pandas is a great python module for data manipulation. In this entire tutorial, I will show you how to do pandas sort by column using different cases. The method for doing this task is done by pandas.sort_values(). The syntax for this method is given below.

pandas.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last',)

by: Names of columns you want to do the sorting.

axis: It has 0 and 1 value. To sort row-wise use 0 and to sort column-wise use 1. The default value of it is 0.

ascending: True or false value. The default is True. If you set False then sorting will be done in descending order.

kind: Kind of sorting method. You can use it from anyone in ‘quicksort’, ‘mergesort’, ‘heapsort’.

na_position: It allows you to put the null values or empty values at the end or start after sorting. The default value is “last”.

Before demonstrating all the examples let’s first create a very simple dataframe. It will be helpful in explaining in the entire example I have used it here. Use the following code for that.

# df creation
    import pandas as pd
    people = {"Name":["Sahil","Ravish","John","Abhishek","Rohan"],
              "Age":[25,27,20,26,21],"Year":[2018,2017,2019,2018,2015]}
    df = pd.DataFrame(people)
Sample DataFrame Creation for Sorting
Sample DataFrame Creation for Sorting

There are two ways you can sort the pandas dataframe. In ascending order and descending order. Below are the examples for each order.

How to sort Pandas Dataframe by column an ascending order?

Here I will try to sort the pandas dataframe in ascending order on the age columns. To do so you have to use the sort_values()method on the dataframe.

Run the following code.

# ascending order sorting by age column
df.sort_values(by=["Age"],inplace=True)
print(df)

Output

Sorting Pandas Dataframe by column in an ascending order
Sorting Pandas Dataframe by column in an ascending order

How to sort Pandas Dataframe by column in descending order?

To sort the dataframe in descending order you have to set the ascending=False inside the sort_values() method.

# descending order sorting by age column
df.sort_values(by=["Age"], inplace=True,ascending=False)
print(df)

Output

Sorting Pandas Dataframe by column in an Descending order
Sorting Pandas Dataframe by column in an Descending order

Sort Dataframe by two columns

The above example was to sort the values of the dataframe using one column. In this section, you will learn how to sort a pandas dataframe by two columns. This type of sorting is useful when there is a repetition of the same values.

For example In our sample dataframe there is two same values in the “Year ” column that is 2018. If you make sorting by two columns then the sort_values() method takes care of it.

# sorting by age and year
df.sort_values(by=["Age","Year"], inplace=True)
print(df)

Output

Sorting Pandas Dataframe by age and year
Sorting Pandas Dataframe by age and year
# sorting by Name and Year
df.sort_values(by=["Name", "Year"], inplace=True)
print(df)

Output

Sorting Pandas Dataframe by Name and Year
Sorting Pandas Dataframe by Name and Year

You can see in both the output the values that are is lower or alphabetically order are printed first in the corresponding 2018 values.

How to permanently sort pandas dataframe by column?

There is a lot of cases when the coder forgets to pass inplace= True inside the sort_values() method. Due to this sorted values are not permanently sorted. To Permanently sort it you have to set the inplace parameter to True.

You can see in all the above examples I have used inplace= True.

How to sort columns by mean in pandas?

If your dataframe have integer or float values. Then you can sort columns by mean of it. For example, I can sort the dataframe using the reindex() method. Just execute the following code.

mean_df = df.reindex(df.mean().sort_values().index, axis=1)
print(mean_df)

Output

Sort columns by mean in pandas
Sort columns by mean in pandas

End Notes

These are some good examples of doing Pandas Sort by Column. Hope you have liked all the example above. In case you have any query then you can contact us for more information. Full code and Output of the entire tutorial is below.

Full Code

import pandas as pd


def main():
    # df creation
    people = {"Name": ["Sahil", "Ravish", "John", "Abhishek", "Rohan"],
              "Age": [25, 27, 20, 26, 21], "Year": [2018, 2017, 2019, 2018, 2015]}
    df = pd.DataFrame(people)
    print(df)
    print("############################################")

    # ascending order sorting by age
    df.sort_values(by=["Age"], inplace=True)
    print(df)
    print("############################################")
    # descending order sorting by age
    df.sort_values(by=["Age"], inplace=True, ascending=False)
    print(df)
    print("############################################")
    # sorting by age and year
    df.sort_values(by=["Age", "Year"], inplace=True)
    print(df)
    print("############################################")
    # sorting by Name and Year
    df.sort_values(by=["Name", "Year"], inplace=True)
    print(df)

    print("############################################")
    mean_df = df.reindex(df.mean().sort_values().index, axis=1)
    print(mean_df)


if __name__ == '__main__':
    main()

Output

Outptut For the Pandas Sort by Column
Outptut For the Pandas Sort by Column

Source:

Official Numpy Sorting Documentation

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner