Pandas groupby 对每个组的值进行排序,并根据每个组的最大值对数据帧组进行排序 [英] Pandas groupby sort each group values and order dataframe groups based on max of each group

查看:84
本文介绍了Pandas groupby 对每个组的值进行排序,并根据每个组的最大值对数据帧组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 3 列的数据集,我试图将它们分组并以排序的方式打印每个组(基于每个组中的最大值).每组中的记录也必须按顺序排列.

I have a dataset containing 3 columns, I’m trying to group them and print each group in sorted fashion (based on highest value in each group). The records in each group also have to be in sorted fashion.

数据集如下所示.

key1,key2,val
b,y,21
c,y,25
c,z,10
b,x,20
b,z,5
c,x,17
a,x,15
a,y,18
a,z,100

df=pd.read_csv('/tmp/hello.csv')
df['max'] = df.groupby(['key1'])['val'].transform('max')
dff=df.sort_values(['max', 'val'], ascending=False).drop('max', axis=1)

我正在应用变换,因为它按组工作,然后对值进行排序.

I'm applying transform as it works per group basis and then sorting the values.

以上代码产生了我想要的数据帧:

Above code results in my desired dataframe:

a,z,100
a,y,18
a,x,15

c,y,25
c,x,17
c,z,10

b,y,21
b,x,20
b,z,5

但是,对于以下数据集,相同的代码失败.

But, the same code fails for below dataset.

key1,key2,val
b,y,10
c,y,10
c,z,10
b,x,2
b,z,2
c,x,2
a,x,2
a,y,2
a,z,2

以下是所需的输出

key1,key2,val
c,y,10
c,z,10
c,x,2

b,y,10
b,x,2
b,z,2

a,x,2
a,y,2
a,z,2

请帮助我为我的场景正确分组和排序数据框.

Please help me in properly grouping and sorting the dataframe for my scenario.

推荐答案

将列 key1 添加到 sort_values 因为在第二个 DataFrame 中有多个最大值 10 每个组,所以排序不能区分组:

Add column key1 to sort_values because in second DataFrame are multiple maximum values 10 per groups, so sorting cannot distingush groups:

df['max'] = df.groupby(['key1'])['val'].transform('max')
dff=df.sort_values(['max','key1', 'val'], ascending=False).drop('max', axis=1)
print (dff)
  key1 key2  val
8    a    z  100
7    a    y   18
6    a    x   15
1    c    y   25
5    c    x   17
2    c    z   10
0    b    y   21
3    b    x   20
4    b    z    5

df['max'] = df.groupby(['key1'])['val'].transform('max')
dff=df.sort_values(['max','key1', 'val'], ascending=False).drop('max', axis=1)
print (dff)
  key1 key2  val
1    c    y   10
2    c    z   10
5    c    x    2
0    b    y   10
3    b    x    2
4    b    z    2
6    a    x    2
7    a    y    2
8    a    z    2

这篇关于Pandas groupby 对每个组的值进行排序,并根据每个组的最大值对数据帧组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆