Pandas GroupBy 将值聚合到字典中,其中包含一列中的键和基于另一列的值

qua*_*fin 2 lookup dictionary group-by dataframe pandas

我正在尝试在 DataFrame 的单元格内创建一个“聚合”字典/类似 JSON 的对象,其中键是根据另一列(对于特定组)的值。下面将通过一个例子来说明这一点。

首先,我从一张我已经叫过的桌子开始.explode

起始表:start_df

孩子ID 父 ID 父母名字 标签id 标签名
12345 100 “扎克” 99 “建造者”
12345 101 “科迪” 67 “水管工”
12345 102 '吉尔' 43 '医生'
12345 102 '吉尔' 47 “哈佛”
67890 108 “艾米丽” 31 '艺术家'
67890 102 '吉尔' 43 '医生'
67890 102 '吉尔' 47 “哈佛”

对于上下文,父级包含子级将继承的标签(属性)。我的目标是创造

目标表:output_df

孩子ID 父 ID 列表 父描述字典 完整标签 ID 列表 标签_祖先
12345 [100、101、102] {100:“扎克”,101:“科迪”,102:“吉尔”} [99、67、43、47] {100: [99], 101: [67], 102: [43, 47] }
67890 [102, 108] {102:'吉尔',108:'艾米丽'} [43、47、31] {102: [43, 47], 108: [31] }

对于列表parent_id_listfull_tag_id_list,我从这里了解到我们可以做类似的事情

start_df.groupby([collection_id], as_index = False).agg({'parent_id': list, 'tag_id': list})
Run Code Online (Sandbox Code Playgroud)

...但是我们如何生成字典parent_desc_dicttag_ancestry?简单地替换listdict不会完成这项工作,因为它将行号作为字典的键而不是parent_id. 我认为做到这一点的方法是使用 lambda 函数,但不确定如何将其与.agg.

Shu*_*rma 6

让我们使用自定义agg函数groupby + apply

def agg(g):
    return pd.Series({
        'parent_id_list': [*g['parent_id'].unique()],
        'parent_desc_dict': dict(zip(g['parent_id'], g['parent_name'])),
        'full_tag_id_list': [*g['tag_id']],
        'tag_ancestry': g.groupby('parent_id')['tag_id'].agg(list).to_dict()
    })


df.groupby('child_id').apply(agg)
Run Code Online (Sandbox Code Playgroud)
           parent_id_list                        parent_desc_dict  full_tag_id_list                           tag_ancestry
child_id                                                                                                                         
12345     [100, 101, 102]  {100: 'Zack', 101: 'Cody', 102: 'Jill'}  [99, 67, 43, 47]  {100: [99], 101: [67], 102: [43, 47]}
67890          [108, 102]              {108: 'Emily', 102: 'Jill'}      [31, 43, 47]             {102: [43, 47], 108: [31]}
Run Code Online (Sandbox Code Playgroud)