I have a df with two columns and I want to combine both columns ignoring the NaN values. The catch is that sometimes both columns have NaN values in which case I want the new co
We can make this problem even more complete and have a universal solution for this type of problem.
The key things in there are that we wish to join a group of columns together but just ignore NaN
s.
Here is my answer:
df = pd.DataFrame({'foodstuff':['apple-martini', 'apple-pie', None, None, None],
'type':[None, None, 'strawberry-tart', 'dessert', None],
'type1':[98324, None, None, 'banan', None],
'type2':[3, None, 'strawberry-tart', np.nan, None]})
df=df.fillna("NAN")
df=df.astype('str')
df["output"] = df[['foodstuff', 'type', 'type1', 'type2']].agg(', '.join, axis=1)
df['output'] = df['output'].str.replace('NAN, ', '')
df['output'] = df['output'].str.replace(', NAN', '')