在数据帧的多索引数据中按索引和值进行排序

2024-10-02 20:44:19 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧,如下所示:

    year    month   message
0   2018    2   txt1
1   2017    4   txt2
2   2019    5   txt3
3   2017    5   txt5
4   2017    5   txt4
5   2020    4   txt3
6   2020    6   txt3
7   2020    6   txt3
8   2020    6   txt4

我想计算出每年前三位的邮件数量。因此,我将数据分组如下:

df.groupby(['year','month']).count()

其结果是:

            message
year    month   
2017    4   1
        5   2
2018    2   1
2019    5   1
2020    4   1
        6   3

两个索引的数据都是按升序排列的。但如何找到如下所示的结果,其中数据按年份(升序)和前n个值的计数(降序)排序。”每月的索引将是免费的

            message
year    month   
2017    5   2
        4   1
2018    2   1
2019    5   1
2020    6   3
        4   1

Tags: 数据messagedf数量邮件yeargroupby升序
3条回答

value_counts默认情况下为您提供排序:

df.groupby('year')['month'].value_counts()

输出:

year  month
2017  5        2
      4        1
2018  2        1
2019  5        1
2020  6        3
      4        1
Name: month, dtype: int64

如果您每年只需要两个顶级值,请执行另一个groupby:

(df.groupby('year')['month'].value_counts()
   .groupby('year').head(2)
)

输出:

year  month
2017  5        2
      4        1
2018  2        1
2019  5        1
2020  6        3
      4        1
Name: month, dtype: int64

您可以使用sort_index,指定ascending=[True,False],以便仅第二级按降序排序:

df = df.groupby(['year','month']).count().sort_index(ascending=[True,False])

              message
year month         
2017 5            2
     4            1
2018 2            1
2019 5            1
2020 6            3
     4            1

这将按年份(升序)和计数(降序)排序

df = df.groupby(['year', 'month']).count().sort_values(['year', 'message'], ascending=[True, False])

相关问题 更多 >