dMb
dMb

Reputation: 9337

pandas: add new column with value from either of two other columns

pd.DataFrame({'A':[None,2,None,None,3,4],'B':[1,2,3,4,5,6]})

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

how do I add column C that will take the value from column A if it's not NaN, otherwise column B's value?

     A  B  C
0  NaN  1  1
1    2  2  2
2  NaN  3  3
3  NaN  4  4
4    3  5  3
5    4  6  4

Upvotes: 2

Views: 943

Answers (2)

crossleyjo
crossleyjo

Reputation: 41

you could also try fillna():

In [26]: a['C'] = a['A'].fillna(a['B'])

In [27]: a
Out[27]:
     A  B  C
0  NaN  1  1
1    2  2  2
2  NaN  3  3
3  NaN  4  4
4    3  5  3
5    4  6  4

Upvotes: 4

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210872

try combine_first():

In [184]: a['C'] = a['A'].combine_first(a['B']).astype(int)

In [185]: a
Out[185]:
     A  B  C
0  NaN  1  1
1  2.0  2  2
2  NaN  3  3
3  NaN  4  4
4  3.0  5  3
5  4.0  6  4

Upvotes: 6

Related Questions