pythonpandasresample

Pandas resample per ID


I have a DataFrame that looks like this

ID    DateHour               Value
A     2024-05-03 07:00:00    5
A     2024-05-03 09:00:00    2
A     2024-05-03 22:00:00    9
A     2024-05-03 23:00:00    1
B     2024-05-03 02:00:00    8
B     2024-05-03 09:00:00    7
B     2024-05-03 20:00:00    8

I would like to resample it hour wise with the ffill method.

What I'm doing now is selecting one ID, resampling and putting all together.

Is there an easier way to do this?

Here is the expected output

ID    DateHour               Value
A     2024-05-03 07:00:00    5
A     2024-05-03 08:00:00    5
A     2024-05-03 09:00:00    2
A     2024-05-03 10:00:00    2
... 
A     2024-05-03 21:00:00    2
A     2024-05-03 22:00:00    9
A     2024-05-03 23:00:00    1
B     2024-05-03 02:00:00    8
B     2024-05-03 03:00:00    8
... 
B     2024-05-03 08:00:00    8
B     2024-05-03 09:00:00    7
... 
B     2024-05-03 19:00:00    7
B     2024-05-03 20:00:00    8

Solution

  • Use groupby with a resample:

    result = df.set_index("DateHour").groupby("ID").resample("h").ffill()