pandas combine two columns with null values

后端 未结 6 1958
醉梦人生
醉梦人生 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:40

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

提交回复
热议问题