如果我想获取基于列id
的过去2个值的平均值,则可以执行以下操作:
df['rolling_mean_2'] = df.groupby('id').apply(lambda x: x.rolling(2, min_periods=2).mean())
>> id value rolling_mean_2
0 b 1 NaN
1 b 3 2
2 d 5 NaN
3 d 7 6
正确,简单。 好的,现在让我说说我的id是具有4个唯一值(a,b,c,d)
的列表形式 x = [{'id': ['a','b','d'], 'value':1},
{'id': ['b','a','d'], 'value':3},
{'id': ['b','a','d'], 'value':5},
{'id': ['a','b','c'], 'value':7}]
df = pd.DataFrame(x)
现在,如何根据列表中包含的唯一值从过去2个值(包括当前行)中获取均值?因此,我的预期输出如下:
我只会使用变量 a 和 d 来保持整洁和简单。
>> id value a_rolling_mean_2 d_rolling_mean_2
0 [a, b, d] 1 NaN NaN
1 [b, a, d] 3 2 2
2 [b, a, d] 5 4 4
3 [a, b, c] 7 6 NaN
答案 0 :(得分:4)
将concat
与数据框构造函数一起使用可重新创建数据框
df=df.rename(columns={'value':'V'})
newdf=pd.concat([df.V,pd.DataFrame(df.id.tolist(),index=df.index)],axis=1)
然后,将melt
与groupby
rolling
mean
和stack
一起使用以得出结果
newdf.reset_index().melt(['index','V']).set_index('index').sort_index().groupby('value').V.rolling(2, min_periods=2).mean().unstack(0)
Out[260]:
value a b c d
index
0 NaN NaN NaN NaN
1 2.0 2.0 NaN 2.0
2 4.0 4.0 NaN 4.0
3 6.0 6.0 NaN NaN