Skip to content
Advertisement

Pandas. How to sort a DataFrame without changing index?

df2 = pd.DataFrame({
    "A": [26, 2, 3],
    "B": [0, 7, 1],
    "C": [7, 5, 4]
},
    index=list('abc'))
df2

Output:

    A  B  C
a  26  0  7
b   2  7  5
c   3  1  4

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

    A  B  C
b   2  7  5
c   3  1  4
a  26  0  7

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:

df2 = pd.DataFrame({
    "A": [26, 2, 3],
    "B": [0, 7, 1],
    "C": [7, 5, 4]
},
    index=list('abc'))
print(df2)

Output:

    A  B  C
a  26  0  7
b   2  7  5
c   3  1  4

Create new dataframe with constructor:

df2 = pd.DataFrame(df2.sort_values(['B', 'A'], ascending=[False, True]).to_numpy(), 
                   index=df2.index, columns=df2.columns)
print(df2)

Output:

    A  B  C
a   2  7  5
b   3  1  4
c  26  0  7

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