0

I need to merge/join two dataframes that have some column names in common, but also have different columns names. For example:

df1 = {A: hello, B: bye, C:good morning, F: nice}
df2 = {A: hola, D: buenos dias, C: adiós, G: bad}

So the resulting dataframe I want is like:

  A   |B     |C            |D           |F    |G  
----------------------------------------------------
hello |bye   |good morning |None        |nice |None
hola  |None  |adiós        |buenos dias |None |bad

I've been trying to merge the dataframes using the 'merge' pandas' function as follows:

res = pandas.merge(df1, df2, on='A')

But I don't get the results I want. Any suggestions?

Thanks!

sooaran
  • 183
  • 1
  • 2
  • 13

1 Answers1

0

First, create your pd.DataFrame objects

df1 = pd.DataFrame({'A': 'hello', 'B': 'bye', 'C':'good morning', 'F': 'nice'}, index=[0])
df2 = pd.DataFrame({'A': 'hola', "D":' buenos dias', 'C':' adiós', 'G': 'bad'}, index=[0])

Then, just use how='outer'

pd.merge(df1, df2, how='outer')

which yields

    A       B   C               F       D           G
0   hello   bye good morning    nice    NaN         NaN
1   hola    NaN adiós           NaN     buenos dias bad
rafaelc
  • 57,686
  • 15
  • 58
  • 82