python - 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())
但这只是给了我每月的评论数量,我不知道如何进一步实现我想要的。
解决方案
我认为这可能是您正在寻找的那种东西:
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
推荐阅读
- javascript - Deno.env 不是函数
- c++ - 为什么一种算法比具有相同时间复杂度的另一种算法更快?
- c# - 在c#中将字节[]复制到3D[]
- django - 向管理页面添加部分
- react-native - 在标题 React Navigation v5 中按下按钮后,React Native(Expo)刷新前一个屏幕
- javascript - 比较不同大小的数组 - D3 JS
- amazon-web-services - 红移时间戳时区
- docker - 如何更改 Dockerfile 中文件夹的权限
- android - 为什么 ViewPager 高度 match_parent 不起作用?
- powerbi - Power BI 报告上 FK 字段上的 Power BI 切片器筛选器