pandas combine two strings ignore nan values

Call fillna and pass an empty str as the fill value and then sum with param axis=1:

In [3]:
df = pd.DataFrame({'a':['asd',np.NaN,'asdsa'], 'b':['asdas','asdas',np.NaN]})
df

Out[3]:
       a      b
0    asd  asdas
1    NaN  asdas
2  asdsa    NaN

In [7]:
df['a+b'] = df.fillna('').sum(axis=1)
df

Out[7]:
       a      b       a+b
0    asd  asdas  asdasdas
1    NaN  asdas     asdas
2  asdsa    NaN     asdsa

Leave a Comment

tech