2

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, but when I am trying to save to excel. It works fine and gets saved but in excel a warning appears in that column saying "Number formatted as text" How to get rid of it, any help?
This is exactly what say notice - it is not recommnded, but if really need it, ignore warning.
3

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

2 Comments

Thanks for editing my question and making it presentable. Any idea how to convert the mixed types into one single type?
@Abul yes! but this question was about merging columns. I suggest you ask another question. We appreciate questions because they present more opportunities to earn upvotes. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.