计算用户在大Pandas中出现频率为30天的次数

2024-03-28 18:20:43 发布

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

我正在处理一个在我的站点上出现users的数据帧。所以我有这样一个数据帧:

dateTime      userId

2018-08-02    17898
2018-08-10    17898
2018-08-25    17898
2018-08-31    17898
2018-08-02    17898
2018-09-06    17898

这里dateTime基本上是该月份出现的第一天。所以我想设定一个30天的门槛,从他们出现的第一天算起,这个人出现了多少天。你知道吗

所以我预期的数据帧是这样的:

userId   n_days_appeared   total_days  first_appearance
17898     4                  30         2018-08-02  

对于每个用户,我都希望这样。你知道吗

所以如果这个人第一次出现在8月5日,那么他的30天就是9月4日,所以我想计算一下这个人在接下来的30天里出现了多少天。你知道吗


Tags: 数据用户datetime站点daysuserstotalfirst
1条回答
网友
1楼 · 发布于 2024-03-28 18:20:43

IIUC,也许可以用这样的东西

df = df.set_index('dateTime')

def n_days_appeared(c): 
    return c[~c.index.duplicated()].count()

def first_appearance(c):
    return c.index.min()

def total_days(c):
    return c.index.max() - c.index.min() + pd.Timedelta(1, unit='d')

df.groupby(['userId',pd.Grouper(freq='M')]).userId.agg([n_days_appeared, 
                                                       first_appearance, 
                                                       total_days])


                     n_days_appeared    first_appearance    total_days
userId  dateTime            
17898   2018-08-31                 4    2018-08-02          30 days
        2018-09-30                 1    2018-09-06          1 days

相关问题 更多 >