0

I have a dataframe:

A B
1 NaN
2 3
4 NaN
5 NaN
6 7

I want to create a new column C containing the value from B that aren't NaN, otherwise the values from A. This would be a simple matter in Excel; is it easy in Pandas?

1 Answer 1

2

Yes, it's simple. Use pandas.Series.where:

df['C'] = df['A'].where(df['B'].isna(), df['B'])

Output:

>>> df
   A    B  C
0  1  NaN  1
1  2  3.0  3
2  4  NaN  4
3  5  NaN  5
4  6  7.0  7

A bit cleaner:

df.C = df.A.where(df.B.isna(), df.B)

Alternatively:

df.C = df.B.where(df.B.notna(), df.A)
Sign up to request clarification or add additional context in comments.

Comments

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.