我希望通过material_id对以下输出进行分组,保留material_description和MPN的唯一值,但列出plant_id。供参考的图片
def search_output(materials):
df=pd.DataFrame(materials)
df_ref = df.loc[:, df.columns!='@search.score'].groupby('material_id').agg({lambda
x:list(x)})
return df_ref此当前按material_id分组,并列出其他列。
下面的代码用于保持按material_id分组的唯一值,但现在我缺少了plant_id列表列。
df_t = df.loc[:, df.columns!='@search.score'].groupby('material_id' ['material_description','MPN'].agg(['unique'])我在找一种把两者结合起来的方法。一种按列分组、保留特定列的唯一值并同时列出其他列的方法。
希望你能帮上忙
发布于 2022-09-21 07:53:09
您可以根据列表创建字典--首先用于按unique进行聚合,然后由list通过dict.fromkeys为所有其他列创建字典,然后将它们连接到GroupBy.agg。
print (df)
material_id material_description MPN A B
0 1 descr1 a b c
1 1 descr2 a d e
2 1 descr1 b b c
3 2 descr3 a b c
4 2 descr4 a b c
5 2 descr4 a b c
u_cols = ['material_description','MPN']
d = {c: 'unique' if c in u_cols else list for c in df.columns.drop('material_id')}
df_ref = df.loc[:, df.columns!='@search.score'].groupby('material_id').agg(d)
print (df_ref)
material_description MPN A B
material_id
1 [descr1, descr2] [a, b] [b, d, b] [c, e, c]
2 [descr3, descr4] [a] [b, b, b] [c, c, c]https://stackoverflow.com/questions/73797132
复制相似问题