如何根据特定列连接两个数据框?

How to concatenate two dataframes based on the particular columns?

有 2 个具有不同列的数据框。 我正在尝试根据前 3 列连接它们。

   a b c X
1  H A 8 1
2  M D 3 2
3  H A 9 3
4  L C 9 4

   a b c Y
1  H A 8 4
2  M D 3 3
3  H A 9 2
4  L C 9 2

这是预期的结果:

   a b c X Y
1  H A 8 1 4
2  M D 3 2 3
3  H A 9 3 2
4  L C 9 4 2

我找不到连接它们的有效方法!!

我认为 merge 应该很好用:

df = pd.merge(df1, df2, on=['a','b','c'])

如果需要动态使用前 3 列:

print (df1.columns[:3].tolist())
['a', 'b', 'c']

df = pd.merge(df1, df2, on=df1.columns[:3].tolist())

print (df)
   a  b  c  X  Y
0  H  A  8  1  4
1  M  D  3  2  3
2  H  A  9  3  2
3  L  C  9  4  2

但如果可能的话,前 3 列在两个 DataFrame 中是不同的,需要由它们连接:

cols = df1.columns[:3].tolist()
df2 = df2.rename(columns=dict(zip(df2.columns[:3], cols)))
df = pd.merge(df1, df2, on=cols)
  • 如果输出顺序无关紧要,
  • 每行a,b,c相同,
  • 每一行的 X 和 Y 都是不同的。

ls1 = [set(['H','A',8,1]), set(['H','A',8,4])]
ls1 = set().union(*ls1)
print ls1
set(['A', 1, 4, 8, 'H'])

new_df = pd.merge(df1, df2)
print (new_df)

output:-       a  b  c  X  Y
            0  H  A  8  1  4
            1  M  D  3  2  3
            2  H  A  9  3  2
            3  L  C  9  4  2