【问题标题】:Pandas: Sort a dataframe based on multiple columnsPandas:根据多列对数据框进行排序
【发布时间】:2020-02-29 13:29:55
【问题描述】:

我知道这个问题已经被问过好几次了。但没有一个答案符合我的情况。

我有一个带有列、部门和雇员计数的熊猫数据框。我需要按降序对employee_count 列进行排序。但如果 2 个employee_counts 之间存在平局,则应根据部门按字母顺序对它们进行排序。

   Department Employee_Count
0    abc          10
1    adc          10
2    bca          11
3    cde          9
4    xyz          15

required output:

   Department Employee_Count
0    xyz          15
1    bca          11
2    abc          10
3    adc          10
4    cde          9

这是我尝试过的。

df = df.sort_values(['Department','Employee_Count'],ascending=[True,False])

但这只是按字母顺序对部门进行排序。

我还尝试先按部门排序,然后再按 Employee_Count。像这样:

df = df.sort_values(['Department'],ascending=[True])
df = df.sort_values(['Employee_Count'],ascending=[False])

这也没有给我正确的输出:

   Department Employee_Count
4    xyz          15
2    bca          11
1    adc          10
0    abc          10
3    cde          9

它先给出'adc',然后给出'abc'。 请帮助我。

【问题讨论】:

    标签: python-3.x pandas sorting dataframe pandas-groupby


    【解决方案1】:

    您可以交换列表中的列以及ascending 参数中的值:

    解释

    列名的顺序是排序的顺序,首先按Employee_Count降序排序,如果Employee_Count中有重复,则按Department排序只会重复行升序。

    df1 = df.sort_values(['Employee_Count', 'Department'], ascending=[False, True])
    print (df1)
      Department  Employee_Count
    4        xyz              15
    2        bca              11
    0        abc              10 <-
    1        adc              10 <-
    3        cde               9
    

    或者为了测试如果使用第二个False,那么重复的行正在排序descending

    df2 = df.sort_values(['Employee_Count', 'Department',],ascending=[False, False])
    print (df2)
      Department  Employee_Count
    4        xyz              15
    2        bca              11
    1        adc              10 <-
    0        abc              10 <-
    3        cde               9
    

    【讨论】:

    • 非常感谢。正是我想要的输出。你能告诉我交换列的理由吗?
    • 它按列表的顺序对列进行排序。