如何在一组pandas Dataframe中设置所有值的联合?

Abh*_*jan 3 python pandas

数据帧的前两行,df:

0|50331648|{1,2,3,4,5}|6  
1|50331649|{3,5,7,8}|2  
Run Code Online (Sandbox Code Playgroud)

执行操作后,我只需要一个包含的集合 {1,2,3,4,5,7,8}.

怎么实现呢?

Nic*_*eli 5

假设"B"是要考虑的列名,您可以set.union在获取的解压缩列表上使用:

set.union(*df['B'].tolist())
{1, 2, 3, 4, 5, 7, 8}
Run Code Online (Sandbox Code Playgroud)

(要么)

将这些作为可调用函数提供给reduce:

from functools import reduce      # If you're on Py3k
reduce(set.union, df['B'].tolist())
{1, 2, 3, 4, 5, 7, 8}
Run Code Online (Sandbox Code Playgroud)

数据:

df = pd.DataFrame(dict(A=[50331648, 50331649],
                       B=[{1,2,3,4,5}, {3,5,7,8}],
                       C=[6,2])
                 )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述