Skip to content
Advertisement

Sort DataFrame based on part of its index

What I would like to achieve

I have a DataFrame whose indices are “ID (int) + underscore (_) + name (str)”. I would like to sort the data based on the ID.

JavaScript

What I tested

I tried to use sort_index and failed.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html

To be honest, I’m stuck at the debug of lambda.

JavaScript

Environment

Python 3.10.5
Pandas 1.4.3

Advertisement

Answer

Try df.sort_index with custom key=:

JavaScript

Prints:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement