2

I am trying to merge two dataframes with a single column. I have looked for the solution in other questions, but without success.

Given the dataframes

import pandas as pd

df1 = pd.DataFrame({'x': [1, 2, 3, 4]})
df2 = pd.DataFrame({'x': [1, 2, 3, 5, 6]}

the desired output is

x_1 | x_2
1   | 1
2   | 2
3   | 3
4   | NaN
NaN | 5
NaN | 6

How can I achieve this result using pandas?

If I understand correctly, I cannot exploit either the column itself or the indexes to use pd.merge.
I could not get the result even using pd.concat([df1, df2], axis=1).

Thank you for your time and help

Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • 2
    You can `merge`: `df1.merge(df2, left_on='x', right_on=df2['x'], how='outer')` – mozway Jun 16 '23 at 10:47
  • Thank you! This is exactly the desired result and it works even by inverting the dataframes. I'm sorry that the question was closed and I can't approve your answer (I had already seen the similar question, but had not found the answer). Thank you again – Leonardo Jun 16 '23 at 10:51

0 Answers0