假设我有一个数据帧,如下所示:
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
value_counts
默认情况下为您提供排序:输出:
如果您每年只需要两个顶级值,请执行另一个groupby:
输出:
您可以使用
sort_index
,指定ascending=[True,False]
,以便仅第二级按降序排序:这将按年份(升序)和计数(降序)排序
相关问题 更多 >
编程相关推荐