Blaze Tama
Blaze Tama

Reputation: 10948

Python Pandas group datetimes by hour and count row

This is my transaction dataframe, where each row mean a transaction :

date               station
30/10/2017 15:20    A
30/10/2017 15:45    A
31/10/2017 07:10    A
31/10/2017 07:25    B
31/10/2017 07:55    B

I need to group the start_date to a hour interval and count each city, so the end result will be:

date        hour      station   count
30/10/2017  16:00        A       2
31/10/2017  08:00        A       1
31/10/2017  08:00        B       2

Where the first row means from 15:00 to 16:00 on 30/10/2017, there are 2 transactions in station A

How to do this in Pandas?

I tried this code, but the result is wrong :

df_start_tmp = df_trip[['Start Date', 'Start Station']]

times = pd.DatetimeIndex(df_start_tmp['Start Date'])

df_start = df_start_tmp.groupby([times.hour, df_start_tmp['Start Station']]).count()

Thanks a lot for the help

Upvotes: 6

Views: 8323

Answers (1)

BENY
BENY

Reputation: 323396

IIUC size+pd.Grouper

df.date=pd.to_datetime(df.date)
df.groupby([pd.Grouper(key='date',freq='H'),df.station]).size().reset_index(name='count')
Out[235]: 
                 date station  count
0 2017-10-30 15:00:00       A      2
1 2017-10-31 07:00:00       A      1
2 2017-10-31 07:00:00       B      2

Upvotes: 14

Related Questions