Home > Net >  take a conditional mean in pandas
take a conditional mean in pandas

Time:11-06

I have a data set like this:

enter image description here

I want to take the mean of LCR in each year for WFR=1 and WFR=0 separately, for example in 2018 I have 4 WFR=0 so take the mean of LCR for it and for WFR=1 I have just one. any idea? thanks

CodePudding user response:

You can groupby by year and WFR. This will create every combination that exists in your dataset. If all conditions are not in your dataframe you can create a base dataframe with all conditions and merge with it.

df = data_new4.groupby(['CLOSDATE_year', 'WFR'])['LCR'].mean()

to plot the data you can use the seaborn library.

import seaborn as sns

sns.lineplot(data=df, hue='WFR', x='CLOSDATE_year', y='LCR')

CodePudding user response:

Try with groupby:

>>> data.groupby(["CLOSDATE_year", "WFR"])["LCR"].mean()

CLOSDATE_year  WFR
2011           1      268.750000
2012           1      235.533333
2018           0      192.775000
               1      186.000000
Name: LCR, dtype: float64
  • Related