Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sort Two Columns by Descending Order in Pandas?

I have this dataframe df consisting of two columns ID and Date:

ID    Date
4    1/1/2008
3    1/1/2007
2   9/23/2010
2    6/3/1998
2    1/1/2001 # Note this date should be before "6/3/1998" for ID# 2
1   4/30/2003

I want to sort df by ID and Date in descending order (largest --> smallest), but this seems not working when I tried the following script:

print df.sort_values(by=["ID", "Date"], ascending=["False", "False"])

The output should in this descending order:

ID    Date
4    1/1/2008
3    1/1/2007
2   9/23/2010
2    1/1/2001 
2    6/3/1998
1   4/30/2003

Any idea how can I sort the date in the correct descending order?

like image 286
MEhsan Avatar asked Aug 01 '16 16:08

MEhsan


Video Answer


1 Answers

You will first need to convert type of Date column from String to Date.

df['Date'] = pd.to_datetime(df['Date'], format="%m/%d/%Y")

Now you can use df.sort_values

print df.sort_values(by=["ID", "Date"], ascending=[False, False]) 

Output :

   ID       Date
0   4 2008-01-01
1   3 2007-01-01
2   2 2010-09-23
4   2 2001-01-01
3   2 1998-06-03
5   1 2003-04-30

In your code, for ascending argument you are passing string "False" , but it should be bool False

like image 95
RAVI Avatar answered Nov 14 '22 23:11

RAVI