Pandas groupby 滚动删除索引列

问题描述

不确定我是否做错了什么(Pandas 1.2.5):

ids = pd.DataFrame(data=range(10),columns=['Id'])
dt = pd.DataFrame(pd.date_range('2021-01-01','2021-01-10',freq='D'),columns=['Date'])
df = ids.merge(dt,how='cross')
df['Val'] = np.random.randint(1,10,size=len(df))
df.set_index(['Id','Date'],inplace=True)
df['Val'].groupby('Id').rolling(window=3).mean()

我希望结果包括日期列(否则为什么要计算滚动平均值?)但日期不存在:

Id
0          NaN
0          NaN
0     2.333333
0     3.333333
0     3.666667
        ...   
9     5.000000
9     4.000000
9     5.000000
9     5.333333
9     6.000000
Name: Val,Length: 100,dtype: float64

我错过了什么?

此外,df['Val'].reset_index('Id').groupby('Id').rolling(window=3).mean() 似乎以某种方式工作,但即使 Id 在 groupby 中传递,它也会将 as_index=False 作为数据列和索引列返回。很奇怪!

                Id  Val
Id  Date        
0   2021-01-01  NaN NaN
    2021-01-02  NaN NaN
    2021-01-03  0.0 7.000000
    2021-01-04  0.0 6.333333
    2021-01-05  0.0 4.666667
... ... ... ...

解决方法

我觉得这样更干净,

ids = pd.DataFrame(data=range(10),columns=['Id'])
dt = pd.DataFrame(pd.date_range('2021-01-01','2021-01-10',freq='D'),columns=['Date'])
df = ids.merge(dt,how='cross')
df['Val'] = np.random.randint(1,10,size=len(df))
df.set_index(['Id'],inplace=True)
df.groupby(['Id']).rolling(window=3,on='Date').mean()#.head(60)

唯一的变化是不在索引中包含“日期”,并滚动 on='Date'