4

Is it possible to get the min and max values from two series in a groupby?

For example in the following situation, when grouping by c, how can I get the min and max values for a and b at the same time?

df = pd.DataFrame({'a': [10,20,3,40,55], 'b': [5,14,8,50,60], 'c': ['x','x','y','y','y']})
g = df.groupby(df.c)
for key, item in g:
    print (g.get_group(key), "\n")

    a   b  c
0  10   5  x
1  20  14  x

    a   b  c
2   3   8  y
3  40  50  y
4  55  60  y

I have resolved this by taking the min and max of each grouped series then by finding the min and max of the _min/_max series:

df['a_min'] = g['a'].transform('min')
df['a_max'] = g['a'].transform('max')
df['b_min'] = g['b'].transform('min')
df['b_max'] = g['b'].transform('max')
df['min'] = df[['a_min', 'a_max', 'b_min', 'b_max']].min(axis=1)
df['max'] = df[['a_min', 'a_max', 'b_min', 'b_max']].max(axis=1)

    a   b  c  a_min  a_max  b_min  b_max  min  max
0  10   5  x     10     20      5     14    5   20
1  20  14  x     10     20      5     14    5   20
2   3   8  y      3     55      8     60    3   60
3  40  50  y      3     55      8     60    3   60
4  55  60  y      3     55      8     60    3   60

This produces the output that I want but with a lot of extra series. I am wondering if there is a better way to do this?

Alex
  • 6,610
  • 3
  • 20
  • 38

2 Answers2

4

Use:

df = df.join(df.melt('c').groupby('c')['value'].agg(['min','max']), 'c')
print (df)
    a   b  c  min  max
0  10   5  x    5   20
1  20  14  x    5   20
2   3   8  y    3   60
3  40  50  y    3   60
4  55  60  y    3   60

Details:

Need one column with a and b values by melt:

print (df.melt('c'))
   c variable  value
0  x        a     10
1  x        a     20
2  y        a      3
3  y        a     40
4  y        a     55
5  x        b      5
6  x        b     14
7  y        b      8
8  y        b     50
9  y        b     60

Then aggregate min and max by groupby and agg:

print(df.melt('c').groupby('c')['value'].agg(['min','max']))
   min  max
c          
x    5   20
y    3   60

and last join to original.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
3

Using transformstill ok , you just need add min(axis=1) for your transform result

df['min'],df['max']=df.groupby('c').transform('min').min(1),df.groupby('c').transform('max').max(1)
df
Out[88]: 
    a   b  c  min  max
0  10   5  x    5   20
1  20  14  x    5   20
2   3   8  y    3   60
3  40  50  y    3   60
4  55  60  y    3   60

In an instance where there are series that you don't want included, for example excluding f, the series should be listed after the grouping

    a   b  c   f
0  10   5  x   0
1  20  14  x  45
2   3   8  y  67
3  40  50  y  17
4  55  60  y  91

df['min'] = df.groupby('c')[['a', 'b']].transform('min').min(axis=1)
df['max'] = df.groupby('c')[['a', 'b']].transform('max').max(axis=1)
Alex
  • 6,610
  • 3
  • 20
  • 38
BENY
  • 317,841
  • 20
  • 164
  • 234