pandas combine two columns with null values

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

    You can always fill the empty string in the new column with None

    import numpy as np
    
    df['new_col'].replace(r'^\s*$', np.nan, regex=True, inplace=True)
    

    Complete code:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'foodstuff':['apple-martini', 'apple-pie', None, None, None], 'type':[None, None, 'strawberry-tart', 'dessert', None]})
    
    df['new_col'] = df['foodstuff'].fillna('') + df['type'].fillna('')
    
    df['new_col'].replace(r'^\s*$', np.nan, regex=True, inplace=True)
    
    df
    

    output:

        foodstuff   type    new_col
    0   apple-martini   None    apple-martini
    1   apple-pie   None    apple-pie
    2   None    strawberry-tart strawberry-tart
    3   None    dessert dessert
    4   None    None    NaN
    

提交回复
热议问题