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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With