熊猫中的聚合集

时间:2021-03-24 16:14:31

标签: python pandas set pandas-groupby aggregate

我有一张这样的桌子:

col1    col2
a       {...}
a       {...}
b       {...}
c       {...}
c       {...}
c       {...}

其中 col2 由集合组成。我需要按 col1 进行聚合,使得 col2 是集合的并集。

到目前为止我最好的尝试是这样的:

def set_union(*sets):
    return reduce(lambda a, b: a.union(b), sets)

mytable.groupby('col1', as_index=False)['equivalente_new'].agg(set_union)

产生的结果:

<块引用>

ValueError: 必须产生聚合值

有没有人有解决办法?

1 个答案:

答案 0 :(得分:3)

删除函数签名中的 splat

def set_union(sets):
    return reduce(lambda a, b: a.union(b), sets)

mytable.groupby('col1', as_index=False).agg(set_union)

  col1       col2
0    a     {1, 2}
1    b        {3}
2    c  {4, 5, 6}

我更喜欢这个(没有减少)

def set_union(sets):
    return set().union(*sets)

mytable.groupby('col1', as_index=False).agg(set_union)
相关问题