繁体   English   中英

pandas groupby中两个系列的最大值和最小值

[英]Max and min from two series in pandas groupby

是否可以从组中的两个系列中获取最小值和最大值?

例如,在以下情况下,当按c分组时,如何同时获取ab的最小值和最大值?

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

我已经抓住每一个分组系列的最小值和最大值,然后通过发现的最小和最大的解决了这个_min / _max系列:

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

这产生了我想要的输出,但有很多额外的系列。 我想知道是否有更好的方法来做到这一点?

使用:

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

细节

需要一列含有ab值的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

然后通过groupbyagg聚合minmax

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

最后join原创。

使用transform仍然可以,您只需要为transform结果添加min(axis=1)

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

在存在您不想包含的系列的实例中,例如排除f ,系列应在分组后列出

    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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM