Peter
Peter

Reputation: 2370

Pandas: left join multiple dfs and update NaN values

I have a df with IDs

   id
0   1
1   2
2   3
3   4

and need to "left-join" (or left-merge) several data frames to it, one after another.

    id   text
0    1  Hello
1    2  World
2  100  Hello

and

    id   text
0    3  World
1  101  Hello

Note: I can not load all dfs at once because of RAM.

A standard "left-join"...

import pandas as pd
df1 = pd.DataFrame({'id': [1,2,3,4]})
df2 = pd.DataFrame({'id': [1,2,100],
                    'text': ['Hello', 'World','Hello']})
df3 = pd.DataFrame({'id': [3,101],
                    'text': ['World', 'Hello']})

m1 = pd.merge(left=df1, right=df2, on="id", how="left")
m2 = pd.merge(left=m1, right=df3, on="id", how="left")

...gives me:

   id text_x text_y
0   1  Hello    NaN
1   2  World    NaN
2   3    NaN  World
3   4    NaN    NaN

However, I would like to "update" the right-joined column so that I get:

   id text
0   1  Hello
1   2  World
2   3  World
3   4    NaN

Is there a way to do this with pd.merge?

Upvotes: 1

Views: 571

Answers (2)

BENY
BENY

Reputation: 323326

This is more like a update problem

df1['text']=np.nan
df1.set_index('id',inplace=True)
df1.update(df2.set_index('id'))
df1.update(df3.set_index('id'))
df1.reset_index(inplace=True)
df1
Out[54]: 
   id   text
0   1  Hello
1   2  World
2   3  World
3   4    NaN

Upvotes: 3

Erfan
Erfan

Reputation: 42916

Are you looking for something like this?

First we use np.where to conditionally fill our text column, after that we drop the columns we dont need.


m2['text'] = np.where(m2.text_x.isnull(), m2.text_y, m2.text_x)
m2.drop(['text_x', 'text_y'], axis=1, inplace=True)


    id  text
0   1   Hello
1   2   World
2   3   World
3   4   NaN

Explanation

np.where works as following:
np.where(condition, true value, false value)

Upvotes: 2

Related Questions