Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas : Merge values to same column (replace missing values by merging dataframes)

I’m sure this has been asked before, but I can’t seem to find a solution.

Consider the following dataframes:

df1 = pd.DataFrame({
    'Letters':('A','B','C','D','E','F'),
    'Position':(1,np.nan,3,4,np.nan,6)
})

df2 = pd.DataFrame({
    'Letters':('B','E'),
    'Position':(2,5)
})

I want to replace the missing values in df1 with their corresponding value in df2. However, when I merge as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I end up with 2 Position columns as follows:

enter image description here

when I want:

enter image description here

How can I achieve this? Thank you in advance.

>Solution :

We can use the fillna method to get the expected result :

df['position'] = df['position_x'].fillna(df['position_y'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading