How can I retain the Date index after a groupby / rolling operation on a Multiindexed Dataframe?

Creating the following example DataFrame:

import pandas as pd
df = pd.DataFrame(data=[[1, 1, 10, 20], [1, 2, 30, 40], [1, 3, 50, 60],
                        [2, 1, 11, 21], [2, 2, 31, 41], [2, 3, 51, 61]],
                  columns=['id', 'date', 'd1', 'd2'])
df.set_index(['id', 'date'], inplace=True)

The DataFrame looks like this:

>>> df
         d1  d2
id date
1  1     10  20
   2     30  40
   3     50  60
2  1     11  21
   2     31  41
   3     51  61

Now, I want to apply a function (sum in the example) on a moving window, on the column d1, and I care about keeping the id and the date as indexes in the end.

I would do this:

df = df.groupby(level='id').rolling(window=2)['d1'].sum()

The output I obtain has the following format (in Pandas 1.1.5):

>>> df

id
1      NaN
1     40.0
1     80.0
2      NaN
2     42.0
2     82.0
Name: d1, dtype: float64

I have seen other examples online, where the output is actually what I want:

>>> df

id      date
1          1      NaN
1          2     40.0
1          3     80.0
2          1      NaN
2          2     42.0
2          3     82.0
Name: d1, dtype: float64

How do I obtain this output? What am I doing wrong?

Answer

Just change from directly create to assign

out = df.set_index(['id', 'date'])['d1']
out[:] = df.groupby('id').rolling(window=2)['d1'].sum().values
out
Out[180]: 
id  date
1   1        NaN
    2       40.0
    3       80.0
2   1        NaN
    2       42.0
    3       82.0
Name: d1, dtype: float64