Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于特定列连接两个数据帧?_Python_Join_Merge_Append_Concat - Fatal编程技术网

Python 如何基于特定列连接两个数据帧?

Python 如何基于特定列连接两个数据帧?,python,join,merge,append,concat,Python,Join,Merge,Append,Concat,有两个数据帧具有不同的列。 我试图根据前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 我找不到一个有效的方法来连接它们 我认为应该好好工作: df =

有两个数据帧具有不同的列。 我试图根据前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
我找不到一个有效的方法来连接它们

我认为应该好好工作:

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())

但如果可能,前3列在两个
数据帧中不同,需要通过它们连接:

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)
打印ls1
集合(['A',1,4,8,'H']))


您尝试的低效方法是什么?请添加解释。
cols = df1.columns[:3].tolist()
df2 = df2.rename(columns=dict(zip(df2.columns[:3], cols)))
df = pd.merge(df1, df2, on=cols)
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