how to aggregate pandas date to days from hourly in python

You can use the groupby method to group the DataFrame by day and then apply an aggregate function to get the daily value from hourly data. Here is the code:

main.py
import pandas as pd

# create sample DataFrame with hourly data
data = {'date': pd.date_range('2021-01-01', periods=24, freq='H'),
        'value': range(24)}
df = pd.DataFrame(data)

# group by day and sum the values
daily_data = df.groupby(pd.Grouper(key='date', freq='D'))['value'].sum()

print(daily_data)
310 chars
12 lines

This code creates a DataFrame with hourly data for one day and then uses the groupby method to group the data by day using the Grouper function with a frequency of 'D' for day. Finally, the sum of the values for each day is calculated using the sum function.

The output will be a Series with the sum of values for each day:

main.py
date
2021-01-01    276
Freq: D, Name: value, dtype: int64
58 chars
4 lines

related categories

gistlibby LogSnag