我有以下几只熊猫dataframe
EventID Institution_Name
TimeCreated
2021-03-22 15:34:46 40 H1
2021-03-22 18:17:19 40 H2
2021-03-22 20:37:47 40 H2
2021-03-22 20:40:20 40 H2
2021-03-22 21:37:32 40 H2
2021-03-22 22:16:32 40 H2
2021-03-22 23:19:49 40 H2
2021-03-22 23:26:40 40 H2
2021-03-23 00:26:03 40 H3
2021-03-23 01:25:43 40 H4
2021-03-23 04:00:24 40 H5
2021-03-23 13:09:42 40 H6
2021-03-23 13:13:23 40 H1
2021-03-23 15:49:33 40 H7
2021-03-23 17:22:30 40 H8
2021-03-23 17:22:37 40 H8
2021-03-23 17:23:49 40 H9
2021-03-23 18:19:56 40 H2
2021-03-23 18:22:14 40 H2
2021-03-23 18:52:36 40 H10
我想计算每个机构每天的事件数量,并按降序排序,同时保持天数的升序。 最终的结果是这样的-
TimeCreated Institution_Name EventID_count
2021-03-22 H2 7
2021-03-22 H1 1
....
2021-03-23 H2 2
and so on
我使用的是:
grouper = df.groupby([pd.Grouper(freq='1D'), 'Institution_Name'])
grouper['EventID'].count().reset_index().sort_values(['TimeCreated'],ascending=True).sort_values('EventID', ascending=False).head(5)
but this does not give the desired result.
可以使用^{} 获取分组日期。按^{} 聚合计数,然后对列进行排序,如下所示:
如果
TimeCreated
是索引,则可以使用df.index.normalize()
,如下所示:结果:
您的代码实际上非常接近(因为
TimeCreated
是一个索引),只需更改列的排序方式,如下所示:这些代码的结果与上面相同,只是
EventID
的列名仍然是EventID
,而不是EventID_count
您可以使用^{} :
输出:
您最初的尝试不起作用,因为Grouper不知道在哪里可以找到您的日期(默认情况下,它使用索引)。这里有两种解决方法
定义列名:
将列用作索引:
相关问题 更多 >
编程相关推荐