I want to merge a Two columns in a database:
The two columns are
A
1
2
Na
Na
B
Na
Na
C
Na
Output
D
1
2
C
Na
You can use combine_first or fillna:
df['D'] = df['A'].combine_first(df['B'])
Or:
df['D'] = df['A'].fillna(df['B'])
Notice:
If one column is numeric and another not, get mixed types and some functions can be broken.
Use combine_first
df.A.combine_first(df.B)
Consider the dataframe df
df = pd.DataFrame(dict(A=[1, 2, np.nan, np.nan], B=[np.nan, np.nan, 'C', np.nan]))
Then
df.A.combine_first(df.B)
0 1
1 2
2 C
3 NaN
Name: A, dtype: object
You can assign it to a new column 'C'
df.assign(C=df.A.combine_first(df.B))
A B C
0 1.0 NaN 1
1 2.0 NaN 2
2 NaN C C
3 NaN NaN NaN