groupby 保留所有先前的字段

我有重复的条目需要合并。id1除了名为和 的两个字段之外,所有字段都是相同的id2- 这些是列表字段,我想组合它们的条目。以下是我仅对id1和id2字段执行此操作的方法:


summary_df = df.groupby(['path_md5']).agg(

    id1 =('id1', lambda x: str(sorted({id for ids in x.dropna() for id in ids}))),

    id2 =('id2', lambda x: str(sorted({id for ids in x.dropna() for id in ids}))),

)

然而,我不想添加 60 个额外的字段,first这样我就可以获取它们的价值。有一个更好的方法吗?这是我想要的输入/输出的示例:


id1     id2     path_md5       other_fields (could be 50 fields -- all the same)...

[1,2]   [3]     abc            ...

[7]     [9]     abc            ...

[17]    [11]    xyz            ...

结果应该是:


id1        id2     path_md5       other_fields...

[1,2,7]   [3,9]     abc            ...

[17]      [11]      xyz            ...

最好的方法是什么?


我尝试执行以下操作:


# Dedupe path, combining id1, id2

agg_fields = [col_name for col_name in df.columns if col_name not in ('id1', 'id2')]

raw_df = raw_df.groupby(agg_fields).agg(...).reset_index()

但它给了我零结果(也许是因为很多值都是空的?


慕斯王
浏览 47回答 1
1回答

婷婷同学_

您可以构建一个聚合字典:agg_dict = {k:'first' for k in df.columns if k not in ['id1','id2','path_md5']}agg_dict['id1'] = lambda x: str(sorted({id for ids in x.dropna() for id in ids}))agg_dict['id2'] = lambda x: str(sorted({id for ids in x.dropna() for id in ids}))summary_df = df.groupby('path_md5', as_index=False).agg(agg_dict)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python