Python Pandas : group by in group by and average?

前端 未结 2 1790
温柔的废话
温柔的废话 2020-11-22 08:39

I have a dataframe like this:

cluster  org      time
   1      a       8
   1      a       6
   2      h       34
   1      c       23
   2      d       74
          


        
相关标签:
2条回答
  • 2020-11-22 09:26

    I would simply do this, which literally follows what your desired logic was:

    df.groupby(['org']).mean().groupby(['cluster']).mean()
    
    0 讨论(0)
  • 2020-11-22 09:27

    If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

    In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
                .groupby('cluster')['time'].mean())
    Out[59]:
    cluster
    1          15
    2          54
    3           6
    Name: time, dtype: int64
    

    If you want the mean of cluster groups only, then you can use:

    In [58]: df.groupby(['cluster']).mean()
    Out[58]:
                  time
    cluster
    1        12.333333
    2        54.000000
    3         6.000000
    

    You can also use groupby on ['cluster', 'org'] and then use mean():

    In [57]: df.groupby(['cluster', 'org']).mean()
    Out[57]:
                   time
    cluster org
    1       a    438886
            c        23
    2       d      9874
            h        34
    3       w         6
    
    0 讨论(0)
提交回复
热议问题