【问题标题】:convert the dataframe into time intervals from timestamps将数据帧从时间戳转换为时间间隔
【发布时间】:2022-01-19 15:20:21
【问题描述】:

我的数据框如下所示

user   action created_at
user1   A     2021-12-15 11:58:53.217258
user1   A     2021-12-15 11:50:27.864876
user1   B     2021-12-15 14:23:27.864876
user1   A     2021-12-15 14:23:27.864876
user3   C     2021-12-15 12:48:09.044315
user3   D     2021-12-15 12:48:09.044315
user4   A     2021-12-15 14:48:09.044315
   

我想要以下内容。其中总动作是动作的频率

                            11-12   12-13 ... 14-15
user   total_action  action 
user1    3             A       2        0        1
user1    1             B       0        0        1
user3    1             C       0        1        0
user4    1             D       0        1        0
user5    1             A       0        0        1

这里的 11-12、12-13 是时间间隔(可以是字符串格式,没有问题)。我曾尝试查看pd.Grouper,但这也无济于事。

【问题讨论】:

    标签: python pandas datetime time-series


    【解决方案1】:

    这是pd.crosstab

    (pd.crosstab([df.user, df.action],df.created_at.dt.hour, 
                      margins=True, margins_name='total_action')
         .iloc[:-1] # remove column total
    )
    

    输出:

    created_at    11  12  14  total_action
    user  action                          
    user1 A        2   0   1             3
          B        0   0   1             1
    user3 C        0   1   0             1
          D        0   1   0             1
    user4 A        0   0   1             1
    

    或者您可以将groupby 与石斑鱼一起使用,例如:

    (df.groupby(['user','action', pd.Grouper(key='created_at', freq='H')])
          .size().unstack(fill_value=0)
          .reset_index()
         )
    

    输出:

    created_at   user action  2021-12-15 11:00:00  2021-12-15 14:00:00  2021-12-15 12:00:00
    0           user1      A                    2                    1                    0
    1           user1      B                    0                    1                    0
    2           user3      C                    0                    0                    1
    3           user3      D                    0                    0                    1
    4           user4      A                    0                    1                    0
    

    您可以添加total_action 列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-22
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2020-12-04
      • 1970-01-01
      相关资源
      最近更新 更多