【问题标题】:Aggregate sets in pandas大熊猫中的聚合集
【发布时间】:2021-06-21 09:40:03
【问题描述】:

我有一张这样的桌子:

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: 必须产生聚合值

有人有解决办法吗?

【问题讨论】:

    标签: python pandas set pandas-groupby aggregate


    【解决方案1】:

    删除函数签名中的 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-28
      • 2022-12-16
      • 2020-01-10
      • 2021-07-03
      • 2015-01-03
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多