Q:

python access a column after groupby

I would like to replace null value of stadium attendance (affluence in french) with their means. Therefore I do this to have the mean by seasons / teams :
test = data.groupby(['season','domicile']).agg({'affluence':'mean'})

This code works and give me what I want (data is dataframe) :
        affluence
season  domicile    
1999    AS Monaco   10258.647059
        AS Saint-Etienne    27583.375000
        FC Nantes   28334.705882
        Girondins de Bordeaux   30084.941176
        Montpellier Hérault SC  13869.312500
        Olympique Lyonnais  35453.941176
        Olympique de Marseille  51686.176471
        Paris Saint-Germain     42792.647059
        RC Strasbourg Alsace    19845.058824
        Stade Rennais FC    13196.812500
2000    AS Monaco   8917.937500
        AS Saint-Etienne    26508.750000
        EA Guingamp     13056.058824
        FC Nantes   31913.235294
        Girondins de Bordeaux   29371.588235
        LOSC    16793.411765
        Olympique Lyonnais  34564.529412
        Olympique de Marseille  50755.176471
        Paris Saint-Germain     42716.823529
        RC Strasbourg Alsace    13664.875000
        Stade Rennais FC    19264.062500
        Toulouse FC     19926.294118
 ....

So now I would like to do a condition on the season and the team. For example test[test.season == 1999]. However this doesn't work because I have only one column 'affluence'. It gives me the error :
'DataFrame' object has no attribute 'season'

I tried :
test = data[['season','domicile','affluence']].groupby(['season','domicile']).agg({'affluence':'mean'})

Which results as above. So I thought of maybe indexing the season/team, but how ? And after that how do I access it ?
Thanks

A:

Doing test = data.groupby(['season','domicile'], as_index=False).agg({'affluence':'mean'}) should do the trick for what you're trying to do.
The parameter as_index=False is particularly useful when you do not want to deal with MultiIndexes.
Example:
import pandas as pd

data = {
    'A' : [0, 0, 0, 1, 1, 1, 2, 2, 2],
    'B' : list('abcdefghi')
}

df = pd.DataFrame(data)
print(df)   
#    A  B
# 0  0  a
# 1  0  b
# 2  0  c
# 3  1  d
# 4  1  e
# 5  1  f
# 6  2  g
# 7  2  h
# 8  2  i

grp_1 = df.groupby('A').count()
print(grp_1)
#    B
# A   
# 0  3
# 1  3
# 2  3

grp_2 = df.groupby('A', as_index=False).count()
print(grp_2)
#    A  B
# 0  0  3
# 1  1  3
# 2  2  3

