python - Python pandas:在另一列中查找具有窗口值的 GroupBy 上的滚动统计信息(例如,中位数)
问题描述
我正在做涉及时间序列的分析。
DataFrame 是这样的:
ID | 姓名 | 行动 | 自行动以来的分钟数 | # 连续打开动作 |
---|---|---|---|---|
1 | 亚历克斯 | 打开 | NaN(或 0) | 1 |
2 | 克里斯 | 打开 | NaN(或 0) | 1 |
3 | 亚历克斯 | 打开 | .0 | 2 |
4 | 克里斯 | 打开 | .12 | 2 |
5 | 克里斯 | 关 | .12 | 0 |
6 | 克里斯 | 打开 | .12 | 1 |
7 | 亚历克斯 | 打开 | .24 | 3 |
我正在尝试获取有关连续打开操作之间的时间延迟的统计信息(即,我的窗口值由“#连续打开操作”确定)。
理想情况下,输出将是这样的(这里是中位数,但可以是任何其他统计数据,例如均值):
ID | 姓名 | 行动 | 自行动以来的分钟数 | # 连续打开动作 | 连续打开操作的中位时间 |
---|---|---|---|---|---|
1 | 亚历克斯 | 打开 | 钠 | 1 | 0 |
2 | 克里斯 | 打开 | NaN(或 0) | 1 | 0 |
3 | 亚历克斯 | 打开 | .0 | 2 | 0.05 |
4 | 克里斯 | 打开 | .12 | 2 | .06 |
5 | 克里斯 | 关 | .12 | 0 | 0 |
6 | 克里斯 | 打开 | .12 | 1 | .12 |
7 | 亚历克斯 | 打开 | .24 | 3 | 0.1 |
这个主题非常接近,但没有集成 GroupBy 条件:Python Pandas rolling mean with window value in another column。
非常感谢。
**编辑:**解决方案
过了一段时间,我想到了……
# this function receives expanding groupby series (i.e., x series if x values) => compute median on last consecutive elements
def find_median(x, windows):
win = windows.iloc[len(x)-1]
# catch it how you want it
if win == 0:
return 0
return pd.Series(x).iloc[-win::].median()
# this function receives consecutively groupby series (i.e., 2 series if 2 users)
def expand_groupby(x):
# get all my counters and use it as an argument
windows = x['consecutive_open']
return x['nb_minutes_since_action'].expanding().apply(lambda x: find_median(x, windows))
tmp = df.sort_values('ID').set_index('ID').groupby('Name').apply(expand_groupby).reset_index()
tmp = tmp.rename(columns={'nb_minutes_since_action': 'median_mn_consecutive_open'})
df.merge(tmp[['ID', median_mn_consecutive_open]], how='left').sort_values(['Name', 'ID'])
解决方案
推荐阅读
- javascript - 在 react native expo 中使用 flex 将同一行上的 2 张卡片与动态内容对齐
- javascript - Vuejs 组合 API - 属性更改
- django - Django 媒体图像显示空白框
- ruby-on-rails - 升级到 Rails 6 后:Content-Disposition 标头现在添加了奇怪的文件名*=UTF-8
- azure-cli - 是否有任何系统方法可以找到每个 Azure CLI 命令所需的最低访问权限或角色?
- javascript - 使用 API 渲染数据
- sql - SQL 中的高效(线性时间)嵌套查询
- python - 构建数据矩阵时如何处理“索引越界”?
- anaconda - conda-forge 存储库是否需要 Anaconda 商业版许可证?
- php - Google Big Query insertAll() 返回成功结果,但表为空