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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With