0

Here is my dataframe

    col1    col2
0   1.0     5.0
1   2.0     6.0
2   NaN     7.0
3   3.0     8.0

I want to add the column('col3') which has the value col1 or col2 as value condition. Col3 value is same to col1 but except if col1 value is 'NaN' then col3 value is set to col2.

My expected output is.

    col1    col2   col3
0   1.0     5.0    1.0
1   2.0     6.0    2.0
2   NaN     7.0    7.0
3   3.0     8.0    3.0

How can I do that?

이대환
  • 1
  • 1

1 Answers1

0

pandas has a builtin function for that: combine_first

df["col3"] = df["col1"].combine_first(df["col2"])
Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36