我有重復的條目需要合并。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, id2agg_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()但它給了我零結果(也許是因為很多值都是空的?
1 回答

婷婷同學_
TA貢獻1844條經驗 獲得超8個贊
您可以構建一個聚合字典:
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)
添加回答
舉報
0/150
提交
取消