user12435479
user12435479

Reputation:

How to merge two dataframes and keep the non -nan values in it

df1



0      Name       phone     Marks

1      mark       1225      20.0

2     charles     165498    36.5

3     oscar       1567      nan

4     bucky       13579     22.0

5     austin      13654     nan


df2

0      Name       phone     Marks

1      mark       1225      nan

2     charles     165498    nan

3     oscar       1567      25,64,65,78,32

4     bucky       13579     22.0

5     austin      13654     21,989,3,48,6357,649,2

How to merge these two df in this way

0      Name       phone     Marks

1      mark       1225      20.0

2     charles     165498    36.5

3     oscar       1567      25,64,65,78,32

4     bucky       13579     22.0

5     austin      13654     21,989,3,48,6357,649,2

If i try merge left. I'll miss out oscar and austin marks, if i try right i'll miss out mark and charles marks. Tried outer also, but could'nt figure them out

How to merge them based on Names ?

Upvotes: 1

Views: 1208

Answers (3)

Pyd
Pyd

Reputation: 6159

you can also use,
df1.fillna(df2.fillna(df1))

Upvotes: 0

luigigi
luigigi

Reputation: 4215

You can simply do:

df1.update(df2)

Output:

0     Name   phone                   Marks
1     mark    1225                      20
2  charles  165498                    36.5
3    oscar    1567          25,64,65,78,32
4    bucky   13579                    22.0
5   austin   13654  21,989,3,48,6357,649,2

Upvotes: 5

visibleman
visibleman

Reputation: 3315

I think this is easier to achieve with combine_first

 df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
 df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
 df1.combine_first(df2)

Upvotes: 3

Related Questions