简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM