Skip to main content
 首页 » 编程设计

python之集合两列上的 Pandas 并集

2024年10月17日30jackei

我在包含集合的数据框中有两列。

如何获得一个新列,其中每一行都包含来自各个列的项目的并集?

例如:

col1 : [{1,2} , {4,5}] 
col2 : [{1,6} , {7,5}] 
union : [{1,2,6}, {4,5,7}] 

一个天真的尝试:

df['union'] = df['col1'].apply(lambda x: x.union(df['col2'])) 

不工作

请您参考如下方法:

我觉得你很亲密 - 使用 apply axis=1:

import pandas as pd 
 
df = pd.DataFrame([[{1,2} , {1,6}], [{4,5} , {7,5}]], columns=['col1', 'col2']) 
 
df['union'] = df.apply(lambda x: x['col1'].union(x['col2']), axis=1) 
print (df) 
     col1    col2      union 
0  {1, 2}  {1, 6}  {1, 2, 6} 
1  {4, 5}  {5, 7}  {4, 5, 7} 

| 的另一种解决方案 docs :

df['union'] = df.apply(lambda x: (x['col1'] | x['col2']), axis=1) 
print (df) 
     col1    col2      union 
0  {1, 2}  {1, 6}  {1, 2, 6} 
1  {4, 5}  {5, 7}  {4, 5, 7}