Python Pandas: Group datetime column into hour and minute aggregations Python Pandas: Group datetime column into hour and minute aggregations pandas pandas

Python Pandas: Group datetime column into hour and minute aggregations


Can't you do, where df is your DataFrame:

times = pd.to_datetime(df.timestamp_col)df.groupby([times.hour, times.minute]).value_col.sum()


Wes' code didn't work for me. But the DatetimeIndex function (docs) did:

times = pd.DatetimeIndex(data.datetime_col)grouped = df.groupby([times.hour, times.minute])

The DatetimeIndex object is a representation of times in pandas. The first line creates a array of the datetimes. The second line uses this array to get the hour and minute data for all of the rows, allowing the data to be grouped (docs) by these values.


Came across this when I was searching for this type of groupby. Wes' code above didn't work for me, not sure if it's because changes in pandas over time.

In pandas 0.16.2, what I did in the end was:

grp = data.groupby(by=[data.datetime_col.map(lambda x : (x.hour, x.minute))])grp.count()

You'd have (hour, minute) tuples as the grouped index. If you want multi-index:

grp = data.groupby(by=[data.datetime_col.map(lambda x : x.hour),                       data.datetime_col.map(lambda x : x.minute)])