2
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.

2
  • 1
    Its not randomly shuffled. It retains the row index after sorting. Commented Nov 4, 2020 at 20:02
  • Correct, I have phrased that badly. Commented Nov 4, 2020 at 20:04

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.