Pandas – create new column from values in other columns on condition

Question:

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
Asked By: jmich738

||

Answers:

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'])]
Answered By: 吴慈霆
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.