根据列表列连接两个 pandas 数据框

2023-12-22

I have 2 个数据框包含列表的列。
我想join他们基于2+ 共同价值观在名单上。例子:

ColumnA ColumnB        | ColumnA ColumnB        
id1     ['a','b','c']  | id3     ['a','b','c','x','y', 'z']
id2     ['a','d,'e']   | 

在这种情况下我们可以看到id1 与 id3 匹配因为列表中有 2 个以上的共享值。因此输出将是(列名称并不重要,仅作为示例):

    ColumnA1 ColumnB1     ColumnA2   ColumnB2        
    id1      ['a','b','c']  id3     ['a','b','c','x','y', 'z']
    

我怎样才能达到这个结果?我尝试迭代数据帧#1 中的每一行,但这似乎不是一个好主意。
谢谢你!


使用行的笛卡尔积并检查每一行

代码内联记录

df1 = pd.DataFrame(
    {
        'ColumnA': ['id1', 'id2'],
        'ColumnB': [['a','b','c'], ['a','d','e']],
    }
)

df2 = pd.DataFrame(
    {
        'ColumnA': ['id3'],
        'ColumnB': [['a','b','c','x','y', 'z']],
    }
)

# Take cartesian product of both dataframes
df1['k'] = 0
df2['k'] = 0
df = pd.merge(df1, df2, on='k').drop('k',1)
# Check the overlap of the lists and find the overlap length
df['overlap'] = df.apply(lambda x: len(set(x['ColumnB_x']).intersection(
                                   set(x['ColumnB_y']))), axis=1)
# Select whoes overlap length > 2
df = df[df['overlap'] > 2]
print (df)

Output:

  ColumnA_x  ColumnB_x ColumnA_y           ColumnB_y  overlap
0       id1  [a, b, c]       id3  [a, b, c, x, y, z]        3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据列表列连接两个 pandas 数据框 的相关文章

随机推荐