Brian
Brian

Reputation: 63

Create a new column in Pandas Dataframe based on the 'NaN' values in another column

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?

Upvotes: 0

Views: 1603

Answers (1)

user17242583
user17242583

Reputation:

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)

Upvotes: 2

Related Questions