0

I'm trying to create a new column by merging non nans from two other columns.
I'm sure something similar has been asked and I've looked at many questions but most of them seems to check the value and return a hard coded values.
Here is my sample code:

    test_df = pd.DataFrame({
    'col1':['a','b','c',np.nan,np.nan],
    'col2':[np.nan,'b','c','d',np.nan]
})
print(test_df)
    col1 col2
0    a  NaN
1    b    b
2    c    c
3  NaN    d
4  NaN    NaN

What I need to add col3 based on checking:
if col1 is not nan then col1
if col1 is nan and col2 not nana then col2
if col1 is nan and col2 is nan then nan

    col1 col2 col3
0    a  NaN    a
1    b    b    b
2    c    c    c
3  NaN    d    d
4  NaN    NaN  NaN
jmich738
  • 1,565
  • 3
  • 24
  • 41

1 Answers1

0
test_df['col3'] = [x1 if pd.notna(x1) else x2 if pd.notna(x2) else np.nan for x1, x2 in zip(test_df['col1'], test_df['col2'])]
吴慈霆
  • 523
  • 2
  • 15