+4 votes
in Python by (1.5k points)
I have a dataframe with columns q,w,f so how can I sort the dataframe by column w in ascending order and by column f in descending order?

1 Answer

+2 votes
by (10.9k points)
edited by

For older versions, you may use the sort() method

df.sort(['q', 'w'], ascending=[True, False])

Nowadays, we don’t use the sort() method as it got removed in the 0.20.0 release. To sort a dataframe in python pandas by two or more columns you can use the following code-

df.sort_values(['q', 'w'], ascending=[True, False])

Ex- Let's create a DataFrame first,

Creating a data frame:

import pandas as pd

import numpy as np

 df = {'Topic':pd.Series(['A','B','C','D']),



 a = pd.DataFrame(df)

print a

Then sorting in ascending order:

df.sort_values(by=['slno', 'pgno'],ascending=[True,False])


Slno  Topic   Pgno

   1        A        11

   2        B        12

   3        C        13

   4        D       14