将数据帧中的一列与另一数据帧中的多列相匹配的最佳方法

2024-07-08 08:03:02 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个df1:

df1 = pd.DataFrame({'name':['Sara',  'John', 'Christine'],

                   'email': ['sara@example.com', 'john@example.com', 'Christine@example.com']})

df1:

    name       email
0   Sara       sara@example.com
1   John       john@example.com
2   Christine  Christine@example.com

df2:

df2 = pd.DataFrame({'email_id':['sara@example.com',  np.nan , 'flower@example8.com'],

                   'alternate email': ['sara@example.com', 'john.walker@example.com' , 'Christine33@example.com'],
                   'alternate email2': ['sara13@example.com', 'john@example.com', 'Christine@example.com'],
                   'country': ['US', 'BR', 'CA']})

df2:

        email_id            alternate email          alternate email2          country
0   sara@example.com       sara@example.com          sara13@example.com             US
1   NaN                    john.walker@example.com  john@example.com                BR
2   flower@example8.com    Christine33@example.com   Christine@example.com          CA

现在我想将df1中的email列与df2中的[email_id, alternate email, alternate email2]列进行匹配,如果找到匹配项,我就得到name&;国家:

输出:

    name         email                   Match
0   Sara         sara@example.com         US
1   John         john@example.com         BR
2   Christine    Christine@example.com    CA

我使用了以下代码,该代码运行良好:

df1['Match'] = np.where((df1['email'].isin(df2['email_id'])) | (df1['email'].isin(df2['alternate email2'])) | (df1['email'].isin(df2['alternate email'])), df1.country , 0)

但在不同的数据集上,我得到了另一个错误:

ValueError: operands could not be broadcast together with shapes (16622,) (433541,) ()

那么,将df1中的一列与df2中的多列进行匹配并合并每个匹配行的结果的最佳标准方法是什么呢


Tags: namecomidexampleemailjohncountrydf1
1条回答
网友
1楼 · 发布于 2024-07-08 08:03:02

尝试:

其想法是将df1的“电子邮件”合并到COL的每一列中(在df2中以类似电子邮件的名称出现)

cols=['email_id', 'alternate email', 'alternate email2']
out=(pd.concat([df1.merge(df2,left_on='email',right_on=x) for x in cols])
       .drop_duplicates(subset=['name'],ignore_index=True).drop(cols,1))

out的输出:

    name        email                   country
0   Sara        sara@example.com        US
1   John        john@example.com        BR
2   Christine   Christine@example.com   CA

相关问题 更多 >

    热门问题