I have a df with two columns and I want to combine both columns ignoring the NaN values. The trick is that sometimes both columns have NaN values, in which case I want the new column to also have NaN. Here is an example:
df = pd.DataFrame({'foodstuff':['apple-martini', 'apple-pie', None, None, None], 'type':[None, None, 'strawberry-tart', 'dessert', None]}) df Out[10]: foodstuff type 0 apple-martini None 1 apple-pie None 2 None strawberry-tart 3 None dessert 4 None None
I tried using fillna
and solving this problem:
df['foodstuff'].fillna('') + df['type'].fillna('')
and I got:
0 apple-martini 1 apple-pie 2 strawberry-tart 3 dessert 4 dtype: object
Line 4 has become empty. That I am not in this situation is the value of NaN, since both columns of the union are NaN.
0 apple-martini 1 apple-pie 2 strawberry-tart 3 dessert 4 None dtype: object
source share