Python Forum
Pandas Outer merge - 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: Pandas Outer merge (/thread-41992.html)



Pandas Outer merge - skollu826 - Apr-19-2024

I have two data frames
dataframe 1
col1 col2
1 A
1 B
2 C
5 Z
4 Q

dataframe 2

col1 col2
1 A
1 B
2 E
3 X
4 R
4 S
I am performing an outer merge

merge = pd.merge(dataframe1, datagrame2, on="col1", how='outer')
I get

col1 col2_x col2_y
1 A A
1 A B
1 B A
1 B B
2 C E
5 Z NAN
3 NAN X
4 Q R
4 Q S

How do I get the output as below

col1 col2_x col2_y
1 A A
1 B B
2 C E
5 Z NAN
3 NAN X
4 Q R
4 Q S
Any help will be appreciated. Thank you


RE: Pandas Outer merge - Pedroski55 - Apr-20-2024

Can't see how to get what you want, but somewhere near it.

Given

Output:
df1 col1 col2 0 1 A 1 1 B 2 2 C 3 5 Z 4 4 Q
and

Output:
df2 col1 col2 0 1 A 1 1 B 2 2 E 3 3 X 4 4 R 5 4 S
df3 = df1.merge(df2, how="outer", left_index=True, right_index=True, suffixes=('_left', '_right'))
df4 = df3[['col2_left', 'col2_right']]

Output:
df4 col2_left col2_right 0 A A 1 B B 2 C E 3 Z X 4 Q R 5 NaN S



RE: Pandas Outer merge - deanhystad - Apr-20-2024

Your desired output appears arbitrary. I cannot think of any logic which would produce your output, let alone find a pandas function to implement that logic. Why is (1, A, A) good but (1, A, B) bad? If (1, A, B) is bad, why is (1, Q, R) good? Please describe the logic behind your desired output.