Pandas Groupby中两个系列的最大和最小 [英] Max and min from two series in pandas groupby
问题描述
是否可以从groupby中的两个系列中获得最小值和最大值?
Is it possible to get the min and max values from two series in a groupby?
例如,在以下情况下,按c
分组时,如何同时获取a
和b
的最小值和最大值?
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
我已经解决了这个问题,方法是取每个分组序列的最小值和最大值,然后找到_min
/_max
系列的最小值和最大值:
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?
推荐答案
使用transform
仍然可以,您只需为transform
结果添加min(axis=1)
Using transform
still 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
在某些情况下,如果您不想包含某些系列,例如排除f
,则应在分组之后列出该系列
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)
这篇关于Pandas Groupby中两个系列的最大和最小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!