Skip to content
Advertisement

Naturally sorting Pandas DataFrame

I have a pandas DataFrame with indices I want to sort naturally. Natsort doesn’t seem to work. Sorting the indices prior to building the DataFrame doesn’t seem to help because the manipulations I do to the DataFrame seem to mess up the sorting in the process. Any thoughts on how I can resort the indices naturally?

JavaScript

Advertisement

Answer

If you want to sort the df, just sort the index or the data and assign directly to the index of the df rather than trying to pass the df as an arg as that yields an empty list:

JavaScript

Note that df.index = natsorted(df.index) also works

if you pass the df as an arg it yields an empty list, in this case because the df is empty (has no columns), otherwise it will return the columns sorted which is not what you want:

JavaScript

EDIT

If you want to sort the index so that the data is reordered along with the index then use reindex:

JavaScript

Note that you have to assign the result of reindex to either a new df or to itself, it does not accept the inplace param.

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