pandas combine two columns with null values
Use fillna
on one column with the fill values being the other column:
df['foodstuff'].fillna(df['type'])
The resulting output:
0 apple-martini
1 apple-pie
2 strawberry-tart
3 dessert
4 None
fillna
both columns togethersum(1)
to add themreplace('', np.nan)
df.fillna('').sum(1).replace('', np.nan)
0 apple-martini
1 apple-pie
2 strawberry-tart
3 dessert
4 NaN
dtype: object
you can use the combine
method with a lambda
:
df['foodstuff'].combine(df['type'], lambda a, b: ((a or "") + (b or "")) or None, None)
(a or "")
returns ""
if a is None
then the same logic is applied on the concatenation (where the result would be None
if the concatenation is an empty string).