Add GroupBy mean result as a new column in pandas

前端 未结 1 1726
无人及你
无人及你 2021-01-15 04:39

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

    df = pd.DataFrame(
           {\'indicator\': [\'indicator 1\', \'indic         


        
相关标签:
1条回答
  • 2021-01-15 05:32

    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
    
    0 讨论(0)
提交回复
热议问题