对比两个不同数据框的两列,并根据条件创建新列

2024-05-12 13:54:50 发布

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

我需要比较两个不同数据帧中的两列,并需要如下所述的输出:

数据帧1:

file_id FileName
UC1    Action
UC1    Patient
UC1    Auth
UC1    DAO
UC1   Transaction
UC1   Validator
UC2    HCP
UC2  Personnel
UC2   Auth DAO

数据帧2:

file_id FileName
UC0     Action
UC0    Patient   
UC1     Auth
UC1     Bean
UC1     Validator
UC2      HCP
UC2   Auth DAO

输出格式:

file_id FileName    Output
UC0 Action           No
UC0 Patient          No
UC1 Auth             Yes
UC1 Bean             No
UC1 Validator       Yes
UC2 HCP             Yes
UC3 Auth DAO        No

Tags: 数据noauthidactionfilenamevalidatoryes
1条回答
网友
1楼 · 发布于 2024-05-12 13:54:50

^{}与左连接和指示符一起使用:

mask = (df2.merge(df1, 
                  on=['file_id', 'FileName'], 
                  how='left', 
                  indicator=True)['_merge'].eq('both'))

或者用^{}比较MultiIndex

mask = (df2.set_index(['file_id', 'FileName']).index
                  .isin(df1.set_index(['file_id', 'FileName']).index))

并通过^{}创建新列:

df2['Output'] = np.where(mask, 'Yes', 'No')
print (df2)
  file_id   FileName Output
0     UC0     Action     No
1     UC0    Patient     No
2     UC1       Auth    Yes
3     UC1       Bean     No
4     UC1  Validator    Yes
5     UC2        HCP    Yes
6     UC2   Auth DAO    Yes

相关问题 更多 >