0

Two DataFrames (df1, df2), df1 has column ID and df2 has columns ID, flag1, flag2.

I want to merge two DataFrames where all the ID's in df1 should be taken along with flag1,flag2 values.

I have the following line of code.

df3=pd.merge(df1, df2, on=id, how='left')

The output of df3 shows column values only for ID, and there are no values for flag1 and flag2.

The expected result in df3 should be ID, flag1, flag2 with values for flag1 and flag2 from df2.

2
  • Should it be on='ID'? Also your merge code should be working as intended, unless there is no matched ID between the two dataframes. Commented May 24, 2019 at 10:26
  • can you add 2 samples of df1 and df2 which replicates your original dataframe? so we can understand better? thanks Commented May 24, 2019 at 11:04

1 Answer 1

1

Then, simply:

import pandas as pd

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

df2 = pd.DataFrame({'id': [2,4,6],
                    'flag1' : ['a','b','c'],
                    'flag2' : ['aa','bb','cc']})

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

output

   id   flag1   flag2
0   1   NaN NaN
1   2   a   aa
2   3   NaN NaN
3   4   b   bb
4   5   NaN NaN
5   6   c   cc
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, I tried ,but does not seems to be working. still not showing any values for flag1 and flag2.
Please, run my code and check the output. Do you get what I got?
Hi All, Issue is fixed. It was bacause of the datatype issue in ID column. One ID column is of type: object and other of int64.

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.