0
df1 = pd.DataFrame(columns=["x","y","z"])
df2 = pd.DataFrame({"x":[1],"y":[2]}, index=["foo"])

I'm trying to get this result:

       z  x  y
foo  NaN  1  2

I tried

df1.merge(df2,how="outer", on=["x","y"], right_index=True)

which gives the error

MergeError: Can only pass argument "on" OR "left_index" and "right_index", not a combination of both.

However, neither

df1.merge(df2,how="outer", on=["x","y"])

nor

df1.merge(df2,how="outer", left_index=True, right_index=True)

give the desired result...

2
  • 2
    Your first empty DataFrame is fairly pointless. I think you're looking to reindex: df2.reindex(['z', 'x', 'y'], axis=1) Commented Mar 31, 2021 at 20:05
  • Thanks @ALollz. I need df1 because it is not always empty. It depends on the user's input. Commented Mar 31, 2021 at 20:47

2 Answers 2

1

The following command:

    df2.merge(df1, on=['x', 'y'], how='outer')

produces

   x  y    z
0  1  2  NaN

The index is not the one you need, so you can do this instead:

    df2.reset_index().merge(df1, on=['x', 'y'], how='outer').set_index('index')

producing

       x  y    z
index           
foo    1  2  NaN

If you want to remove the word 'index', name the above dataframe df3 and:

    del df3.index.name

resulting in

     x  y    z
foo  1  2  NaN
Sign up to request clarification or add additional context in comments.

Comments

0

Why don't just:

df2['z'] = df1['z']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.