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.

Upvotes: 2

Views: 3247

Answers (2)

Scott Boston
Scott Boston

Reputation: 153500

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

Upvotes: 2

NYC Coder
NYC Coder

Reputation: 7604

You can add the index back after sorting:

df2 = df2.sort_values(['B', 'A'], ascending=[False, True]).reset_index(drop=True)
df2['index'] = ['a', 'b', 'c']
df2.set_index('index', inplace=True)

print(df2)

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

Upvotes: 4

Related Questions