Pandas groupby on datetime parts with the dt accessor

Pandas groupby on datetime parts with the dt accessor

If your Python Pandas data frame has a datetime column, you can group on a portion of that via the “dt” accessor.

For example, let’s get mean trip_distance for each hour of the day:

df.groupby(df['tpep_pickup_datetime'].dt.hour)['trip_distance'].mean()