根据特定列组合多个熊猫数据帧

时间:2018-10-27 14:08:06

标签: python pandas dataframe merge

假设我有多个Pandas数据帧,每个数据帧都有多行和多列,其中第一个包含某事物的ID。我想做的非常简单,就是我使用合并,联接,concat等失败了...如果df1和df2的第一列相同,则将第2列附加到df2的末尾到df1,否则跳过它

例如:

dat1={'A':['1', '2', '3'],'B':['4', '7', '11'],
  'C':['5', '8', '12'],'D':['6', '9', '13']}
df1 = pd.DataFrame.from_dict(dat1, orient='index')
dat2={'A':['1', '2', '3'],'B':['4', '7', '11'],
  'C':['5', '8', '12'],'D':['6', '9', '13']}
df2 = pd.DataFrame.from_dict(dat2, orient='index')

在这种情况下,由于两者的第一列都包含A,B,C和D,因此合并的数据帧将具有4行,共6列。

df_merged
   0  1   2  3  4   5
A  1  2   3  1  2   3
B  4  7  11  4  7  11
C  5  8  12  5  8  12
D  6  9  13  6  9  13

如果在第二个数据帧中有一个E而不是B,那么我根本不会合并它们。

2 个答案:

答案 0 :(得分:0)

使用合并

pd.merge(df1,df2,left_index=True,right_index=True)

    0_x 1_x 2_x 0_y 1_y 2_y
A   1   2   3   1   2   3
B   4   7   11  4   7   11
C   5   8   12  5   8   12
D   6   9   13  6   9   13


def myFunc(df1,df2):
    if len(np.intersect1d(df1.index.values, df2.index.values)) == len(df1.index.values) & len(np.intersect1d(df1.index.values, df2.index.values)) == len(df2.index.values):
        df = pd.merge(df1,df2,left_index=True,right_index=True)
        return df
    else:
        pass

答案 1 :(得分:0)

使用pd.concat,将多个DataFrame粘合在一起,然后在所需的轴上合并,方法是从pandas Doc

>>> frames = [df1, df2]

>>> pd.concat(frames, axis=1)
   0  1   2  0  1   2
A  1  2   3  1  2   3
B  4  7  11  4  7  11
C  5  8  12  5  8  12
D  6  9  13  6  9  13
相关问题