Pandas List List Group

Given the data structure, for example:

rule_id | ordering | sequence_id 1 | 0 | 12 1 | 1 | 13 1 | 1 | 14 2 | 0 | 1 2 | 1 | 2 2 | 2 | 12 

I need to convert it to:

 rule_id | sequences 1 | [[12],[13,14]] 2 | [[1],[2],[12]] 

which looks like a simple group in groupby to list the operation - I cannot get it to work in pandas.

 df.groupby(['rule_id', 'ordering'])['sequence_id'].apply(list) 

leaves me with

 rule_id ordering 1 0 [12] 1 [13,14] 2 0 [1] 1 [2] 2 [12] 

How to apply another groupBy operation for further concatenated result in one list?

+5
source share
1 answer

Use another groupby at the first level of MultiIndex :

 df.groupby(['rule_id', 'ordering'])['sequence_id'].apply(list).groupby(level=0).apply(list) 
+2
source

Source: https://habr.com/ru/post/1276227/


All Articles