Question: I have a table which includes `salary` and `company_location`.

I was trying to calculate the mean salary of a country, its works:

```
wage = df.groupby('company_location').mean()['salary']

```

However, I have many with `company_location` which have less than 5 entries, I would like to exclude them from the report.

I know how to calculate countries with the top 5 entries:

```
Top_5 = df['company_location'].value_counts().head(5)

```

I am just having a problem connecting those to variables into one and making a graph out of it...

Thank you.

Answer: 
`expanding.mean`
----------------

```
for c in ('a', 'b'):
    m = df.filter(like=c).expanding(axis=1).mean().iloc[:, 1:]
    df[m.columns.str.replace(r'(\d+)$', r'1_\1', regex=True)] = m

```

#### Result

```
   a1  a2  a3  a4  b1  b2   b3   b4  a1_2      a1_3  a1_4  b1_2       b1_3   b1_4
0   1   4   6  10  15  40   90  100   2.5  3.666667  5.25  27.5  48.333333  61.25
1   2   5   3  11  25  50   90  120   3.5  3.333333  5.25  37.5  55.000000  71.25
2   3   7   9  14  35  55  100  120   5.0  6.333333  8.25  45.0  63.333333  77.50

```

Another option:

```py
out = [value.expanding(axis=1).mean()
            .rename(columns = lambda col: f"{col[0]}1_{col[1]}") 
       for _, value in df.groupby(df.columns.str[0], axis = 1)]

pd.concat([df]+out, axis = 1)
   a1  a2  a3  a4  b1  b2   b3   b4  a1_1  a1_2      a1_3  a1_4  b1_1  b1_2       b1_3   b1_4
0   1   4   6  10  15  40   90  100   1.0   2.5  3.666667  5.25  15.0  27.5  48.333333  61.25
1   2   5   3  11  25  50   90  120   2.0   3.5  3.333333  5.25  25.0  37.5  55.000000  71.25
2   3   7   9  14  35  55  100  120   3.0   5.0  6.333333  8.25  35.0  45.0  63.333333  77.50

```
IIUC, you can reshape with `wide_to_long`, perform a `groupby.rolling`, then `unstack` and flatten the multiindex:

```
df.join(pd
   .wide_to_long(df.reset_index(), stubnames=['a', 'b'], i='index', j='n')
   .groupby(level='index').expanding().mean()
   .loc[lambda d: d.index.get_level_values('n')>1]
   .droplevel(0).unstack('n')
   .pipe(lambda d: d.set_axis(d.columns.map(lambda x: f'{x[0]}1_{x[1]}'), axis=1))
)

```

output:

```
   a1  a2  a3  a4  b1  b2   b3   b4  a1_2      a1_3  a1_4  b1_2       b1_3   b1_4
0   1   4   6  10  15  40   90  100   2.5  3.666667  5.25  27.5  48.333333  61.25
1   2   5   3  11  25  50   90  120   3.5  3.333333  5.25  37.5  55.000000  71.25
2   3   7   9  14  35  55  100  120   5.0  6.333333  8.25  45.0  63.333333  77.50

```