通过多列,熊猫,Python合并多个数据框

时间:2020-07-13 16:25:20

标签: python pandas dataframe

我想按df3-df2-df1的顺序合并多个数据帧。 df3df2首先在df3(id, Feature 1)上被df2(id, Feature 1)合并。但是,df2(id, Feature 2)df1(id, Feature 2)合并在一起。输出如下:

enter image description here

这是我的代码:

import pandas as pd

data1 = {
    'id': ['1', '2', '3', '4', '5'],
    'Feature1': ['K', 'C', 'E', 'G', 'I'],
    'Feature2': ['L', 'N', 'F', 'H', 'J']}

df1 = pd.DataFrame(data1, columns = ['id', 'Feature1', 'Feature2'])

data2 = {
    'id': ['1', '2', '6', '7', '8'],
    'Feature1': ['K', 'M', 'O', 'Q', 'S'],
    'Feature2': ['L', 'N', 'P', 'R', 'T']}
df2 = pd.DataFrame(data2, columns = ['id', 'Feature1', 'Feature2'])

data3 = {
    'id': ['1', '2', '3', '4', '5', '7', '8', '9', '10', '11'],
    'Feature1': ['K', 'M', 'O', 'Q', 'S','X','Y','Z','W','P'],
    'Feature2': ['B', 'D', 'F', 'H', 'J','O', 'Q', 'S','X','Y'],
    'Feature3': [12, 13, 14, 'K', 'M','S', 'Q',15, 16, 17,]}


df3 = pd.DataFrame(data3, columns = ['id', 'Feature1', 'Feature2','Feature3'])

df1df2df3如上图所示。

请问该怎么做?谢谢!

1 个答案:

答案 0 :(得分:1)

赞:

In [114]: df3.merge(df2, on=['id','Feature1'], how='left').merge(df1, left_on=['id','Feature2_y'], right_on=['id','Feature2'], how='left') 
Out[114]: 
   id Feature1_x Feature2_x Feature3 Feature2_y Feature1_y Feature2
0   1          K          B       12          L          K        L
1   2          M          D       13          N          C        N
2   3          O          F       14        NaN        NaN      NaN
3   4          Q          H        K        NaN        NaN      NaN
4   5          S          J        M        NaN        NaN      NaN
5   7          X          O        S        NaN        NaN      NaN
6   8          Y          Q        Q        NaN        NaN      NaN
7   9          Z          S       15        NaN        NaN      NaN
8  10          W          X       16        NaN        NaN      NaN
9  11          P          Y       17        NaN        NaN      NaN