pandas - 按列分组,应用函数创建新列 - 给出不正确的结果

pandas - groupby a column, apply a function to create a new column - giving incorrect results

我有这样的数据:

   Thing   quarter    num_col1    num_col2
    aaa    2010Q1      1.3         99.76
    bbb    2010Q1      11.3        109.76
    ccc    2010Q1      91.3        119.76
   .....
   .....
    aaa    2019Q4      21.3        119.76
    bbb    2019Q4      41.3        299.76
    ccc    2019Q4      201.3       199.76

我需要按 Thing 列分组,并计算所有季度的 num_col1num_col2 列的移动平均值。

这是我到目前为止尝试过的方法:

## define moving-average function
N = 2
def pandas_rolling(x):
    return pd.Series.rolling(x, window=N).mean()

## now group-by and calculate moving averages
things_groupby = df.groupby(by=['Thing'])
## below lines are giving incorrect values
df.loc[:,'num_col1_SMA'] = (things_groupby['num_col1'].apply(pandas_rolling)).values
df.loc[:,'num_col2_SMA'] = (things_groupby['num_col2'].apply(pandas_rolling)).values

但是,当我手动执行 Thing 列中的一项独特操作时,如下所示,它给出了预期的结果。

pandas_rolling(df.loc[df.loc[:,'Topic']=='aaa'].loc[:,'num_col1']).values

计算单个组的移动平均值然后将它们填充到数据框中我做错了什么?我该如何正确执行此操作?

您可以删除 values:

df['num_col1_SMA'] = things_groupby['num_col1'].apply(pandas_rolling)
df['num_col2_SMA'] = things_groupby['num_col2'].apply(pandas_rolling)

或:

df[['num_col1_SMA', 'num_col2_SMA']] = (things_groupby[['num_col1','num_col2']]
                                               .apply(pandas_rolling))

如果可能没有 groupby.apply 是必要的删除第一级 MultiIndex:

df[['num_col1_SMA', 'num_col2_SMA']] = (things_groupby[['num_col1','num_col2']]
                                               .rolling(window=N)
                                               .mean()
                                               .droplevel(0))