+4 votes
2 views
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.7k 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']),

   'Slno':pd.Series([1,2,3,4]),

   'Pgno':pd.Series([11,12,13,14])}

 a = pd.DataFrame(df)

print a

Then sorting in ascending order:

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

Output:

Slno  Topic   Pgno

   1        A        11

   2        B        12

   3        C        13

   4        D       14

...