-1
$\begingroup$

I have two different dataframes, they both share the same labels, "Country" and "Year", I am trying to merge these together as one by these two columns.

This is my code:

joined = pd.merge(left = df, right = df1, on = ["Year", "Country"])

This is the result I receive for joined.head():

0 rows × 34 columns

Any suggestions?

Thanks.

$\endgroup$

1 Answer 1

0
$\begingroup$

Try the following:

new_df = pd.merge(df, df1, how='left', left_on=["Year", "Country"], right_on = ["Year", "Country"])
$\endgroup$
3
  • $\begingroup$ Hi, I tried that, and indeed, it did align these two labels. However, now all of the other data in the columns are all NaN. Can you suggest anything to tweak this? Thanks for the help $\endgroup$ Oct 14, 2020 at 15:50
  • 1
    $\begingroup$ It's difficult to say without seeing your data - but I would consult the following resource to make sure you're merging the way you want to: pandas.pydata.org/pandas-docs/stable/user_guide/merging.html $\endgroup$ Oct 14, 2020 at 15:54
  • $\begingroup$ Forgot to thank you for this, you saved me a great deal of time. Your example had me thinking about the result your code gave and I solved it with a simple concat. Thanks for taking the time. Cheers. $\endgroup$ Oct 27, 2020 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.