汇总数据框中的行并消除重复项

时间:2020-02-05 23:04:25

标签: python pandas concatenation aggregate

我想在df中合并行,因此每个ID /名称都有一个唯一的行,其他值相加(收入)或级联(主题和乘积)。但是,在连接的地方,我不想出现重复项。

我的df与此类似:

ID   Name   Revenue   Subject   Product
123  John   125       Maths     A
123  John   75        English   B
246  Mary   32        History   B
312  Peter  67        Maths     A
312  Peter  39        Science   A

我正在使用以下代码来汇总数据框中的行

def f(x): return ' '.join(list(x))

df.groupby(['ID', 'Name']).agg( 
  {'Revenue': 'sum', 'Subject': f, 'Product': f} 
)

这将导致如下输出:

ID   Name   Revenue   Subject        Product
123 John    200       Maths English  A B
246 Mary    32        History        B
312 Peter   106       Maths Science  A A

如何修改我的代码,以便在串联中删除重复项?因此,在上面的示例中,最后一行在Product中读取了A,而不是A A

1 个答案:

答案 0 :(得分:1)

您非常亲密。列出并加入它们之前,先在物品上套组。这只会返回唯一的项目

def f(x): return ' '.join(list(set(x)))

df.groupby(['ID', 'Name']).agg( 
  {'Revenue': 'sum', 'Subject': f, 'Product': f} 
)
相关问题