Python Forum
How to merge three DataFrames based on specific column - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to merge three DataFrames based on specific column (/thread-29532.html)



How to merge three DataFrames based on specific column - Mekala - Sep-08-2020

Hi,
I have three Data Frames with a common column (ID) and I want to merge them into one.


df1:

ID	Pop	RANK
A1	T1	1
A1	T1	3
B1	T1	4
B2	T1	2
K1	T1	9
K1	T1	1
K2	T1	5
df2:

ID	Pop	TEMP RANK
A1	T1	20	 1
A1	T1	56	 3
B1	T1	72	 4
B2	T1	45	 2
K1	T1	0	 9
K1	T1	20	 1
K2	T1	43	 5
KN	T2	56	 1
KP	T2	23	 5
NH6	T3	56	 23
KL5	T4	19	 16
df3:

ID	Status	RANK
A1	NOR	    1
A1	ABN	    3
B1	HOT	    4
B2	COOL	2
K1	HOT	    9
K1	ER	    1
K2	RAMP	5
KN	BAK	    1
KP	HOT	    5
NH6	COOL	23
KL5	RAMP	16
I want to merge based on ID:

result:
ID	Pop	RANK	TEMP   Status
A1	T1	1	    20	   NOR
A1	T1	3	    56	   ABN
B1	T1	4	    72	   HOT
B2	T1	2	    45	   COOL
K1	T1	9	    0	   HOT
K1	T1	1	    20	   ER
K2	T1	5	    43	   RAMP
when merge, merge TEMP column from df2, and Status column from df3.

I use below code, but it got error:

df1.set_index('ID',inplace=True)
df2.set_index('ID',inplace=True)
df3.set_index('ID',inplace=True)
df = pd.concat([df1,df2,df3],axis=1).reset_index()
df.rename(columns = {'index':'ID'})
ValueError: Shape of passed values is (7, 11), indices imply (7, 9)