如何在 Pandas 中按降序对两列进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38704153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:43:11  来源:igfitidea点击:

How to Sort Two Columns by Descending Order in Pandas?

pythonsortingpandasdataframe

提问by MEhsan

I have this dataframe dfconsisting of two columns IDand Date:

我有这个数据框df由两列IDDate

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 dfby IDand Datein descending order (largest --> smallest), but this seems not working when I tried the following script:

我要排序dfIDDate降序排列(最大- >最小的),但是这似乎当我尝试下面的脚本不工作:

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?

知道如何按正确的降序对日期进行排序吗?

回答by RAVI

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

现在你可以使用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

在您的代码中,对于升序参数,您正在传递 string "False",但它应该是 boolFalse