Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add GroupBy mean result as a new column in pandas

I have a dataframe that gives upper and lower values of each indicator as follows

    df = pd.DataFrame(
           {'indicator': ['indicator 1', 'indicator 1', 'indicator 2', 'indicator 2'],
            'year':[2014,2014,2015,2015],
            'value type': ['upper', 'lower', 'upper', 'lower'],
            'value':[12.3, 10.2, 15.4, 13.2]
           },
           index=[1,2,3,4])

I want to remove the upper and lower values and replace that with the mean of two values.

How can I do that?

like image 837
Abdul-Baqi Sharaf Avatar asked Dec 14 '22 20:12

Abdul-Baqi Sharaf


1 Answers

You could groupby and transform by mean.

df['value'] = df.groupby('indicator')['value'].transform('mean')

df
     indicator  value value type  year
1  indicator 1  11.25      upper  2014
2  indicator 1  11.25      lower  2014
3  indicator 2  14.30      upper  2015
4  indicator 2  14.30      lower  2015

Or, if you want only one row per indicator, use agg.

df = df.groupby('indicator').agg('mean')
df
             value  year
indicator               
indicator 1  11.25  2014
indicator 2  14.30  2015

If you want the index as a column instead, call reset_index:

df = df.reset_index()
df
     indicator  value  year
0  indicator 1  11.25  2014
1  indicator 2  14.30  2015
like image 140
cs95 Avatar answered Dec 16 '22 09:12

cs95