Pandas加入2个数据帧

时间:2015-07-19 17:34:01

标签: python join pandas

我有2个数据帧:

>>> result
         id   order_nr
0   3131334  334756912
0   3131312  386517432
0   3131309  356299432
0   3131205  397514312
          ...

>>> OMSdf
     order_nr            status  refund_amount
0   377766482  already_canceled              0
1   348722582  already_canceled              0
2   395287472           on_hold              0
3   345883652  already_canceled              0
          ...

这两个数据帧在字段中有一些共同的值" order_nr":

>>> result[result['order_nr'] == '377766482']
        id   order_nr
0  3129153  377766482

>>> OMSdf[OMSdf['order_nr'] == '377766482']
    order_nr            status  refund_amount
0  377766482  already_canceled              0

但我尝试将他们加在一起:

resultfinal = result.join(OMSdf, on='order_nr', how='inner', lsuffix='', rsuffix='_oms', sort=False)

结果为空:

>>> resultfinal
Empty DataFrame
Columns: [id, order_nr, order_nr_oms, status, refund_amount]
Index: []

1 个答案:

答案 0 :(得分:2)

使用以下代码

df_merged = pd.merge(result, OMSdf, how='inner')

在您的情况下,您可以在加入之前将order_nr作为两个数据框的索引,如下所示

result.index = result['order_nr']
OMSdf.index = OMSdf['order_nr']