熊猫分组和重新采样

时间:2021-06-08 17:43:04

标签: pandas datetime count grouping resampling

我有以下数据:

id,device,event,timestamp
0,a,something,1990-05-01 00:09:05
1,a,something_else,1990-05-01 00:09:08
2,a,we_dont_care,1990-05-01 00:09:23
3,a,whatever,1990-05-01 00:11:05
4,a,whatsoever,1990-05-01 00:12:32
5,a,ok,1990-05-01 00:12:46
6,b,still_dont_care,1990-05-01 00:13:46
7,b,thats_annoying,1990-05-01 00:14:46
8,b,please_stop,1990-05-01 00:14:55
9,b,really_stop,1990-05-01 00:22:46
10,a,ok,1990-05-01 00:23:43

我想按以下方式对数据进行分组:

device,timestamp,count
a,1990-05-01 00:09,3
a,1990-05-01 00:11,1
a,1990-05-01 00:12,2
a,1990-05-01 00:23,1
b,1990-05-01 00:13,1
b,1990-05-01 00:14,2
b,1990-05-01 00:22,1

其中 timestamp 是修剪为小时的时间戳(因此没有分钟或秒),而 count 只是某个小时内 device 上发生的事件的总和(我们不关心事件的类型,我们只需要总结它们)。请注意,我真的不想按小时分组:

  • 1990-05-01 00:09:051990-05-01 00:09:15 应该组合在一起
  • 1990-05-01 00:09:051990-06-01 00:09:15 不应组合在一起

这就是探查的目的,但它不会重新采样,因此如果设备没有发生任何事件,它将留下空值。相反,我想要一行 count=0:

df_count = df.groupby(["cameraId", df["timestamp"].dt.hour])["id"].count()

1 个答案:

答案 0 :(得分:1)

我们可以使用

>>> df.groupby(df.timestamp.dt.floor('h')).count()
            id  device  event  timestamp
timestamp
1990-05-01  11      11     11         11

使用单独的 device

>>> df.groupby(by=["device", df.timestamp.dt.floor('h')]).count()["event"].reset_index()
  device  timestamp  event
0      a 1990-05-01      7
1      b 1990-05-01      4