首页 > 解决方案 > Pandas - 计算存在指定值的时间窗口数

问题描述

对于我正在做的一个小项目,我有来自特定 Subreddit 的评论数据:

index    author  created_utc  ... body
0        user1   May 20 2018      "..."  
1        user1   Sep 28 2018      "..."  
2        user2   Apr 12 2017      "..."  
3        user7   Sep 22 2018      "..."
...      ...      ...               
32       user2   Jan 1 2018       "..." 

(注意: created_utc是 int 格式1464737845,但为了清楚起见,我在示例中将其写为日期)

我想探索用户参与的寿命。假设我将时间窗口设置为一个月,我想最终得到一个类似的东西:

index    author  time_windows_present  
0        user1             2      
1        user2             2       
2        user7             1      
...      ...      ...               

到目前为止,我已经达到了

comments_df.set_index('created_utc', inplace = True)
print(comments_df.resample('1M')['author'].count())

但这只是给了我每月的评论数量,我不知道如何进一步实现我想要的。

标签: pythonpandas

解决方案


我认为这可能是您正在寻找的那种东西:

def get_month_year(x):
    return str(x.month)+'_'+str(x.year)

df['datetime'] = pd.to_datetime(df['created'])
df['month_year'] = df['datetime'].apply(get_month_year)

#   author      created   datetime  month_year
# 0  user1  May 20 2018 2018-05-20     5_2018
# 1  user1  Sep 28 2018 2018-09-28     9_2018
# 2  user2  Apr 12 2017 2017-04-12     4_2017
# 3  user7  Sep 22 2018 2018-09-22     9_2018
# 4  user2   Jan 1 2018 2018-01-01     1_2018

df.groupby(by=['author','month_year']).count().reset_index()\
                                      .groupby('author')['created'].count()\
                                      .rename('time_windows_present').to_frame()

#         time_windows_present
# author                      
# user1                2
# user2                2
# user7                1

推荐阅读