Skip to content
Advertisement

Pandas. How to sort a DataFrame without changing index?

JavaScript

Output:

JavaScript

df2.sort_values(['B', 'A'], ascending=[False, True]) gives:

JavaScript

The column with indexes is now shuffled in new order, but I want it to be the same even after sorting. Parameter ignore_index just sets indexes from 0 to n-1. And the sort_index function isn’t helpful too, because indexes can be not in lexicographical order.

Advertisement

Answer

Use dataframe constructor:

JavaScript

Output:

JavaScript

Create new dataframe with constructor:

JavaScript

Output:

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