首页 > 解决方案 > 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'])

标签: pythonpandas

解决方案


推荐阅读