Groupby Pandas levels
<p>Similar to my <a href="https://stackoverflow.com/questions/34567349/expanding-mean-over-multiple-series-in-pandas">previous question</a>, I want to split a dataframe by groupby and apply a calculation. </p>

<p>Now I want to introduce a new column to split the calculation over the dataframe. Here is the code:</p>

<pre><code>import pandas as pd
import numpy as np

d = {'year' : [2000, 2000, 2000, 2000, 2001, 2001, 2001],
 'home': ['A', 'B', 'B', 'A', 'B', 'A', 'A'],
 'away': ['B', 'A', 'A', 'B', 'A', 'B', 'B'],
 'aw': [1, 0, 0, 0, 1, 0, np.nan],
 'hw': [0, 1, 0, 1, 0, 1, np.nan]}

df = pd.DataFrame(d, columns=['home', 'away', 'hw', 'aw'])
df.index = range(1, len(df) + 1)
df.index.name = 'game'

df = df.set_index(['hw', 'aw'], append=True).stack().reset_index().rename(columns={'level_3': 'role', 0: 'team'}).loc[:,
 ['game', 'team', 'role', 'hw', 'aw']]

def wins(row):
    if row['role'] == 'home':
        return row['hw']
    else:
        return row['aw']
df['wins'] = df.apply(wins, axis=1)

df['expanding_mean'] = df.groupby('team')['wins'].apply(lambda x: pd.expanding_mean(x).shift())

print df
</code></pre>

<p>Running the above will give the expanding mean over the entire dataframe. But how do I re-start the calculation for each new <code>year</code>?</p>

<p>I have tried adding <code>year</code> to columns= in the df declaration but it is included in <code>role</code> which is not desired. My gap in understanding is in the levels so any enlightenment appreciated. </p>

<p>Edit: desired result below</p>

<pre><code>    game team  role  hw  aw  wins  expanding_mean    year
0      1    A  home   0   1     0             NaN    2000
1      1    B  away   0   1     1             NaN    2000
2      2    B  home   1   0     1        1.000000    2000
3      2    A  away   1   0     0        0.000000    2000
4      3    B  home   0   0     0        1.000000    2000
5      3    A  away   0   0     0        0.000000    2000
6      4    A  home   1   0     1        0.000000    2000
7      4    B  away   1   0     0        0.666667    2000
8      5    B  home   0   1     0             NaN    2001
9      5    A  away   0   1     1             NaN    2001
10     6    A  home   1   0     1        0.000000    2001
11     6    B  away   1   0     0        1.000000    2001
12     7    A  home NaN NaN   NaN        0.500000    2001
13     7    B  away NaN NaN   NaN        0.500000    2001
</code></pre>