Python:如何按数据帧分组以按小时和天数计数?

2024-06-25 23:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据帧:

df.head(4)
    timestamp                  user_id   category
0  2017-09-23 15:00:00+00:00     A        Bar
1  2017-09-14 18:00:00+00:00     B        Restaurant
2  2017-09-30 00:00:00+00:00     B        Museum
3  2017-09-11 17:00:00+00:00     C        Museum

我想计算每个类别每小时的访客数量,并有如下数据框

df 
     year month day   hour   category   count
0    2017  9     11    0       Bar       2
1    2017  9     11    1       Bar       1
2    2017  9     11    2       Bar       0
3    2017  9     11    3       Bar       1

Tags: 数据iddf数量bar类别yearrestaurant
2条回答

要获取每个类别每小时的用户id计数,您可以在datetime中使用groupby:

df.timestamp = pd.to_datetime(df['timestamp'])
df_new = df.groupby([df.timestamp.dt.year, 
                  df.timestamp.dt.month, 
                  df.timestamp.dt.day, 
                  df.timestamp.dt.hour, 
                  'category']).count()['user_id']
df_new.index.names = ['year', 'month', 'day', 'hour', 'category']
df_new = df_new.reset_index()

当数据帧中有日期时间时,可以使用dt访问器,它允许您访问日期时间的不同部分,即年份

假设您想要groupby日期和小时,如果timestamp列是datetime列,则可以使用以下代码

df.year = df.timestamp.dt.year
df.month = df.timestamp.dt.month
df.day = df.timestamp.dt.day
df.hour = df.timestamp.dt.hour
grouped_data = df.groupby(['year','month','day','hour','category']).count()

相关问题 更多 >