markan3
markan3

Reputation: 107

pandas two dataframes, some sort of merge

I have two dataframes like this:

df['one'] = [1,2,3,4,5]
df['two'] = [nan, 15, nan, 22, nan] 

I need some sort of join or merge which will give me dataframe like this:

df['result'] = [1,15,3,22,5]

any ideas?

Upvotes: 2

Views: 184

Answers (2)

tegancp
tegancp

Reputation: 1202

You can use the pandas method combine_first() to fill the missing values from a DataFrame or Series with values from another; in this case, you want to fill the missing values in df['two'] with the corresponding values in df['one']:

In [342]: df['result']= df['two'].combine_first(df['one'])

In [343]: df
Out[343]:
   one  two  result
0    1  NaN       1
1    2   15      15
2    3  NaN       3
3    4   22      22
4    5  NaN       5

Upvotes: 2

Jianxun Li
Jianxun Li

Reputation: 24752

You can use np.where to do it. So if df.two is NaN, you use df.one's value, otherwise use df.two.

import pandas as pd
import numpy as np

# your data
# ========================================
df = pd.DataFrame(dict(one=[1,2,3,4,5], two=[np.nan, 15, np.nan, 22, np.nan]))
print(df)


   one  two
0    1  NaN
1    2   15
2    3  NaN
3    4   22
4    5  NaN    


# processing
# ========================================    
df['result'] = np.where(df.two.isnull(), df.one, df.two)


   one  two  result
0    1  NaN       1
1    2   15      15
2    3  NaN       3
3    4   22      22
4    5  NaN       5    

Upvotes: 2

Related Questions