Group by Columns and use Grouper 8h interval

Viewed 35

I have a df

Animal Starttime dosis
Tiger 2019-02-18 10:06:00 20
Tiger 2019-02-19 10:06:00 2
Fish 2018-02-18 10:06:00 2
Ape 2021-04-10 10:06:00 12
Ape 2021-04-10 12:06:00 2

Target df:

Animal Starttime dosis
Tiger 2019-02-18 16:00:00 20
Tiger 2019-02-19 16:00:00 2
Fish 2018-02-18 16:00:00 2
Ape 2021-04-10 16:00:00 14

In the starting df are different animals with different timestamps for each dose they have received. The desired output is grouped according to the animals and where the doses they received are summed up in the interval of 8h.

It works fine if I just use grouper and freq= 8h but then it gets grouped according to the times and the the animals are ignored. So that's when I tried this out, group first the df and then apply the the grouper object but this does not work.

df.groupby(pd.Grouper(key=('Animal','Starttime'), freq='8h')).sum()

df.groupby('Animal').apply(pd.Grouper(key='Starttime', freq='8h')).sum()

Any help or advice is very much appreciated. thanks

1 Answers

You only need to change the syntax slightly:

df.groupby(["Animal", pd.Grouper(key="Starttime", freq="8h")]).sum()
Related