使用 Pandas 数据帧根据间隙长度计算活动日期

Calculating Active dates based on gap length using Pandas Dataframes

我是 pandas 的新手,正在尝试找出计算此信息的最佳方法,因此非常感谢您的帮助。基本上我有一个看起来像这样的数据框:

id     activity_date
1      2015-01-01      
1      2015-01-02      
1      2015-01-03      
2      2015-01-02      
2      2015-01-05     
3      2015-01-10      

我想计算以下信息 "How many days was each account active?",我知道我可以简单地进行计数来获取此信息,但我想应用以下限制,"If there are n days between activity dates, only count the days before that gap"。

例如,当 n = 5 时,以下应 return 活跃天数为 4,而不是 6

id     activity_date
1      2015-01-01      
1      2015-01-02      
1      2015-01-04
1      2015-01-06
1      2015-01-14
1      2015-01-15

理解你想要的东西之后就简单多了,所以我们计算当前行和前一行之间的差异是否大于 5 天给我们一个布尔系列,我们使用这个过滤器 df 然后使用索引值执行切片:

In [57]:

inactive_index = df[df['activity_date'].diff() > pd.Timedelta(5, 'd')]
inactive_index
Out[57]:
   id activity_date
4   1    2015-01-14

In [18]:

inactive.index
Out[18]:
Int64Index([4], dtype='int64')
In [58]:

df.iloc[:inactive.index[0]]
Out[58]:
   id activity_date
0   1    2015-01-01
1   1    2015-01-02
2   1    2015-01-04
3   1    2015-01-06