Back

Explore Courses Blog Tutorials Interview Questions
+4 votes
3 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?

2 Answers

+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']),

   '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

0 votes
by (106k points)

As of pandas 0.17.0, DataFrame.sort() is deprecated and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

You can use the following video tutorials to clear all your doubts:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Browse Categories

...