pandas combine two columns with null values

后端 未结 6 2017
醉梦人生
醉梦人生 2021-02-03 22:10

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

6条回答
  •  不要未来只要你来
    2021-02-03 22:46

    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 NaNs.

    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', '')
    

提交回复
热议问题