Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

These are my data frames: 

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 the new order, but I want it to be same even after sorting. Parameter ignore_index just sets the indexes from 0 to n-1. And then sort_index function isn't helpful too, because indexes can be not in the lexicographical order.

1 Answer

0 votes
by (36.8k points)

Use the data frame 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 a new data frame 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

 Want to be a master in Data Science? Enroll in this Data Science Courses

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...