Python Pandas-直接将移动平均列从group by添加到dataframe

Python Pandas-直接将移动平均列从group by添加到dataframe,python,pandas,pandas-groupby,moving-average,split-apply-combine,Python,Pandas,Pandas Groupby,Moving Average,Split Apply Combine,我有一个包含以下列的数据框: name, date, day_index, value 我想在同一数据帧中添加第四列,这是每个名称的第三列(值)的指数加权移动平均值,按第一个日期排序,然后按day_索引排序。我可以使用以下代码将其生成为一个系列 df.sort_values(['date','day_index'],inplace=True) ecw_series = df.groupby('name').apply(lambda x: x["value"].ewm(halflife=2)

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

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

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'
如果我尝试将该系列与数据帧合并,则会出现以下错误:

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'
df['index']=df.index
df=df.merge(ecw_series,左_on=['name','index'],右_index=True)

无法将DataFrame与类型为的实例合并以下方法有效:

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

我仍然有点困惑,为什么不能在Lambda函数中引用“value”列

如果按列引用,则必须指定axis=1:
ecw_series=df.groupby('name').apply(lambda x:x[“value”]).ewm(半衰期=2.mean(),axis=1)