Skip to content Skip to sidebar Skip to footer

How To Concat Sets When Using Groupby In Pandas Dataframe?

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, 34, 3, 2]) Now when I

Solution 1:

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:

ab01set([1, 2, 3, 34])
12set([2, 3])
23set([4, 5, 6])

Post a Comment for "How To Concat Sets When Using Groupby In Pandas Dataframe?"