Python 如何基于特定列连接两个数据帧?
有两个数据帧具有不同的列。 我试图根据前3列将它们连接起来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 =
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