【问题标题】:Compare two dataframes and output new column比较两个数据框并输出新列
【发布时间】:2021-09-17 17:57:45
【问题描述】:

我是 Python 的初学者。我有两个数据框,每个都有 5 列,但每个数据框只有前两列有匹配的数据。每个数据帧都有不同数量的记录。我想将 df1A 列与 df2A 列进行比较,如果它们匹配,则输出列来自 df2 的 D (ownerEmail)。如果 A 列不匹配,则 D 列应为空。

df1

subscriptionId | displayName | state   | authorization | tenantId
12345          | DEV_SPS     | Enabled | RoleBased     | 938c49a8
67890          | PROD_LINUX  | Enabled | RoleBased     | 0a9cb9ee
11900          | TST_WIN     | Enabled | RoleBased     | e1513511

df2

subscriptionId | SubName    | Connected | ownerEmail         | organization
12345          | DEV_SPS    | Enabled   | john.doe@gmail.com | Marketing
67890          | PROD_LINUX | Enabled   | alex.bre@gmail.com | Sales

期望的输出

subscriptionId | displayName | state   | authorization | tenantId | ownerEmail       
123456         | DEV_SPS     | Enabled | RoleBased     | 938c49a8 | john.doe@gmail.com
67890          | PROD_LINUX  | Enabled | RoleBased     | 0a9cb9ee | alex.bre@gmail.com
11900          | TST_WIN     | Enabled | RoleBased     | e1513511 | null

我尝试过类似的方法,但没有成功。

df1['ownerEmail'] = np.where(df1['subscriptionId'] == df2['subscriptionId'], ['ownerEmail'], "")
print(df1)

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: python pandas dataframe merge compare


    【解决方案1】:

    合并subscriptionId 列上的数据框并保留来自df1 (how='left') 的所有记录:

    >>> pd.merge(df1.astype({'subscriptionId': str}),
                 df2[['subscriptionId', 'ownerEmail']].astype({'subscriptionId': str}),
                 on='subscriptionId', how='left')
    
       subscriptionId displayName    state authorization  tenantId          ownerEmail
    0           12345     DEV_SPS  Enabled     RoleBased  938c49a8  john.doe@gmail.com
    1           67890  PROD_LINUX  Enabled     RoleBased  0a9cb9ee  alex.bre@gmail.com
    2           11900     TST_WIN  Enabled     RoleBased  e1513511                 NaN
    

    【讨论】:

    • 谢谢。我试过了,但没有工作。 df1.merge(df2[['subscriptionId', 'ownerEmail']], on='subscriptionId', how='left') 它抛出错误“您正在尝试合并对象和 float64 列。如果您希望继续你应该使用 pd.concat"
    • 好的,有一些进展,因为没有错误。但是 ownerEmail 列显示所有记录的 NaN。这是我尝试过的: df3 = pd.merge(df1.astype({'subscriptionId': str}), df2[['subscriptionId', 'ownerEmail']].astype({'subscriptionId': str}), on= 'subscriptionId', how='left') print(df3)
    • 好的,所以我稍微修改了我的数据框并按照您发布的代码进行操作。有用!谨对您的帮助表示感谢。非常感谢:)
    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2018-04-01
    • 2019-03-29
    • 2021-01-17
    相关资源
    最近更新 更多