是否可以从groupby中获得两个系列的最小值和最大值?
例如在下列情况下,通过分组的时候c
,我怎么能得到的最小值和最大值a
,并b
在同一时间?
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
这产生了我想要的输出,但是有很多额外的系列。我想知道是否有更好的方法可以做到这一点?
使用transform
还可以,您只需要添加即可min(axis=1)
获得transform
结果
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句