how to concat sets when using groupby in pandas dataframe?

前端 未结 1 1438
我寻月下人不归
我寻月下人不归 2021-01-18 09:20

This is my dataframe:

> df
       a             b
    0  1         set([2, 3])
    1  2         set([2, 3])
    2  3      set([4, 5, 6])
    3  1  set([1,         


        
相关标签:
1条回答
  • 2021-01-18 10:18

    This might be close to what you want

    df.groupby('a').apply(lambda x: set.union(*x.b))
    

    In this case it takes the union of the sets.

    If you need to keep the column names you could use:

    df.groupby('a').agg({'b':lambda x: set.union(*x)}).reset_index('a')
    

    Result:

        a   b
    0   1   set([1, 2, 3, 34])
    1   2   set([2, 3])
    2   3   set([4, 5, 6])
    
    0 讨论(0)
提交回复
热议问题