Pandas - 直接将group by的移动平均列添加到数据帧

问题描述 投票:0回答:1

我有一个包含以下列的数据框:

name, date, day_index, value

我想在同一个数据帧中添加第4列,这是每个名称的第3列(值)的指数加权移动平均值,按第一个日期排序,然后是day_index。我可以使用以下代码将其生成为一个系列。

df.sort_values(['date','day_index'],inplace=True)

ecw_series = df.groupby('name').apply(lambda x: 
x["value"].ewm(halflife=2).mean())

但是,如果我尝试直接将其添加到原始数据帧,我会收到以下错误:

df['ecw'] =  df.groupby('name').apply(lambda x: 
x["value"].ewm(halflife=2).mean())



incompatible index of inserted column with frame index

如果我尝试将系列与数据帧合并,我会收到以下错误:

df['index'] = df.index

df = df.merge(ecw_series, left_on=['name','index'],right_index=True)

can not merge DataFrame with instance of type <class 
'pandas.core.series.Series'

此时,我正在考虑将系列转换为数据帧,然后合并。但我相信必须有更好的方法。

python pandas pandas-groupby moving-average split-apply-combine
1个回答
0
投票

以下方法有效:

df['ecw'] = model_df.groupby('name')['value'].apply(lambda x: 
 x.ewm(halflife=2).mean())

我仍然有点混淆为什么你不能引用Lambda函数中的'value'列。

© www.soinside.com 2019 - 2024. All rights reserved.