[英]how can i achieve desire output in one liner code?
i have dataframe given below and i want to achieve the output in one liner code.我有下面给出的 dataframe,我想在一个班轮代码中实现 output。 my codes are also attached.我的代码也附上。
df : -totscrd_n_r
FRANK SCORE
1 0.748180912
2 0.288977296
3 0.233826294
4 0.199272093
5 0.175346525
1 0.162129932
2 0.152657008
3 0.144826844
4 0.136572409
5 0.122732783
1 0.288984226
2 0.233826364
3 0.199273169
4 0.175346964
5 0.162130909
1 0.152657357
2 0.144827363
3 0.136572485
4 0.12273334
5 0.050275945
output : - TEMP3_10GRP
FRANK HIGH LOW
1 0.748180912 0.152657357
2 0.288977296 0.144827363
3 0.233826294 0.136572485
4 0.199272093 0.12273334
5 0.175346525 0.050275945
my code:-
TEMP3_10GRPH = pd.DataFrame(totscrd_n_r.groupby(['FRANK'])['SCORE'].max().reset_index())
TEMP3_10GRPH.rename(columns = {'SCORE':'HIGH'}, inplace = True)
TEMP3_10GRPL = pd.DataFrame(totscrd_n_r.groupby(['FRANK'])['SCORE'].min().reset_index())
TEMP3_10GRPL.rename(columns = {'SCORE':'LOW'}, inplace = True)
TEMP3_10GRP = pd.merge(TEMP3_10GRPH, TEMP3_10GRPL, left_on='FRANK', right_on='FRANK', how = 'left')
TEMP3_10GRP
can i achieve this with a shorter way?我可以用更短的方式实现这一目标吗?
Thanks in advance提前致谢
Groupby has a method .agg()
or .aggregate()
specially for this. Groupby 有一个专门用于此的方法.agg()
或.aggregate()
。
df.groupby().agg(['max', 'min'])
You can use .agg
as @ RichieV pointed out,正如@RichieV指出的那样,您可以使用.agg
,
>>> import pandas as pd
>>> ...
>>> df
FRANK SCORE
0 1 0.748181
1 2 0.288977
2 3 0.233826
3 4 0.199272
4 5 0.175347
5 1 0.162130
6 2 0.152657
7 3 0.144827
8 4 0.136572
9 5 0.122733
10 1 0.288984
11 2 0.233826
12 3 0.199273
13 4 0.175347
14 5 0.162131
15 1 0.152657
16 2 0.144827
17 3 0.136572
18 4 0.122733
19 5 0.050276
>>> df.groupby('FRANK').agg(High=pd.NamedAgg(column="SCORE", aggfunc="max"), Low=pd.NamedAgg(column="SCORE", aggfunc="min"))
High Low
FRANK
1 0.748181 0.152657
2 0.288977 0.144827
3 0.233826 0.136572
4 0.199272 0.122733
5 0.175347 0.050276
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.