按特定字段对列进行排序和分组



我有一个对象列表

[
{
"companyid": long,
"parentid": long
"score": long,
...
}
]

parentid不过是母公司的cid
示例数据将类似于以下

cid    parentid score
1      10       1000  
2      10       100
3      10       1001  
10     10       20  
11     100      1000  
12     100      100  
100    100      200  
111    1000     10  
112    1000     100  
1000   100      2000  

我需要根据分数对值进行排序,但我想按parentid对值进行分组
我尝试过这种方法,但它并不真正符合我的要求,因为它先进行分组,然后对进行排序

df.groupby('headcompanyid').apply(lambda x: x.sort_values('score'))

按分数排序会得到以下结果:

cid    parentid score
1000   100      2000 
3      10       1001  
1      10       1000  
11     100      1000  
100    100      200  
2      10       100
112    1000     100  
12     100      100  
10     10       20  
111    1000     10  

根据已排序数据的parentid分组(这是我的最终目标(,应该会给出

cid    parentid score
1000   100      2000 
11     100      1000    // since 100 is the parentid, it needs to be pushed up the in the result set
100    100      200     // if multiple records are pushed up, then sorting should be based on score
12     100      100  
3      10       1001     // 2nd group by is based on 10, since 1001 is the next highest score which  
1      10       1000     // doesn't belong to the 100 parentid group
2      10       100 
10     10       20 
112    1000     100  
111    1000     10 

如果很重要的话,我使用的是pandas v0.24.2和python 3.7

试试这个:

df.sort_values(['parentid', 'score'], ascending=[False, False])

输出:

cid parentid    score
8   112  1000        100
7   111  1000        10
9   1000 100         2000
4   11   100         1000
6   100  100         200
5   12   100         100
2   3    10          1001
0   1    10          1000
1   2    10          100
3   10   10          20

最新更新