【问题标题】:Join pandas dataframes based on column values根据列值加入熊猫数据框
【发布时间】:2017-11-30 14:05:36
【问题描述】:

我对 pandas 数据框很陌生,我在连接两个表时遇到了一些麻烦。

第一个 df 只有 3 列:

DF1:
item_id    position    document_id
336        1           10
337        2           10
338        3           10
1001       1           11
1002       2           11
1003       3           11
38         10          146

第二个有完全相同的两列(还有很多其他列):

DF2
item_id    document_id    col1    col2   col3    ...
337        10             ...     ...    ...
1002       11             ...     ...    ...
1003       11             ...     ...    ...

我需要执行的操作在 SQL 中如下所示:

DF1 join DF2 on 
DF1.document_id = DF2.document_id
and
DF1.item_id = DF2.item_id

因此,我希望看到 DF2,并辅以“位置”列:

item_id    document_id    position    col1   col2   col3   ...

什么是使用 pandas 的好方法?

谢谢!

【问题讨论】:

    标签: python mysql sql pandas dataframe


    【解决方案1】:

    我认为您需要 merge 和默认的 inner 连接,但两列中的值没有重复组合:

    print (df2)
       item_id  document_id col1  col2  col3
    0      337           10    s     4     7
    1     1002           11    d     5     8
    2     1003           11    f     7     0
    
    df = pd.merge(df1, df2, on=['document_id','item_id'])
    print (df)
       item_id  position  document_id col1  col2  col3
    0      337         2           10    s     4     7
    1     1002         2           11    d     5     8
    2     1003         3           11    f     7     0
    

    但如有必要,position 列在位置3

    df = pd.merge(df2, df1, on=['document_id','item_id'])
    cols = df.columns.tolist()
    df = df[cols[:2] + cols[-1:] + cols[2:-1]]
    print (df)
       item_id  document_id  position col1  col2  col3
    0      337           10         2    s     4     7
    1     1002           11         2    d     5     8
    2     1003           11         3    f     7     0
    

    【讨论】:

    • 非常感谢!如此简单又如此优雅:) 这完全解决了问题。
    • 在使用其中一列中的重复 ID 组合时,我可以问您一个可能的解决方案吗?
    • @jezrael 如果我想要一个左连接,我正在寻找右侧与左侧不匹配的项目(用于动态数据结构上的数据有效负载验证)我该怎么做?这是内连接,谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-01-25
    • 2020-12-27
    • 2020-08-08
    • 2017-10-14
    • 2016-05-17
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多