I'm trying to get the first non null value from multiple pandas series in a dataframe.
df = pd.DataFrame({'a':[2, np.nan, np.nan, np.nan],
'b':[np.nan, 5, np.nan, np.nan],
'c':[np.nan, 55, 13, 14],
'd':[np.nan, np.nan, np.nan, 4],
'e':[12, np.nan, np.nan, 22],
})
a b c d e
0 2.0 NaN NaN NaN 12.0
1 NaN 5.0 55.0 NaN NaN
2 NaN NaN 13.0 NaN NaN
3 NaN NaN 14.0 4.0 22.0
in this df I want to create a new column 'f', and set it equal to 'a' if a is not null, 'b' if b is not null etc. down to e.
I could do a bunch of np.where statements which is inefficient.
df['f'] = np.where(df.a.notnull(), df.a,
np.where(df.b.notnull(), df.b,
etc.))
I looked into doing df.a or df.b or df.c etc.
result should look like:
a b c d e f
0 2.0 NaN NaN NaN 12.0 2
1 NaN 5.0 55.0 NaN NaN 5
2 NaN NaN 13.0 NaN NaN 13
3 NaN NaN 14.0 4.0 22.0 14