Categories
Python Answers

How to add custom sorting in a Python Pandas dataframe?

Spread the love

Sometimes, we want to add custom sorting in a Python Pandas dataframe.

In this article, we’ll look at how to add custom sorting in a Python Pandas dataframe.

How to add custom sorting in a Python Pandas dataframe?

To add custom sorting in a Python Pandas dataframe, we call sort_values with the key argument set to a lambda function.

For instance, we write

df.sort_values(by=['m'], key=lambda x: x.map(custom_dict))

to call sort_values with the by column set to an array of columns to sort by.

And the key is set to a lambda function that return values returned by map to map the values in the keys of custom_dict to its values and returned.

Conclusion

To add custom sorting in a Python Pandas dataframe, we call sort_values with the key argument set to a lambda function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *