Python: create a new column from existing columns

前端 未结 6 2032
一生所求
一生所求 2021-02-20 02:48

I am trying to create a new column based on both columns. Say I want to create a new column z, and it should be the value of y when it is not missing and be the value of x when

6条回答
  •  灰色年华
    2021-02-20 03:17

    Use np.where:

    In [3]:
    
    df['z'] = np.where(df['y'].isnull(), df['x'], df['y'])
    df
    Out[3]:
       x   y   z
    0  1 NaN   1
    1  2   8   8
    2  4  10  10
    3  8 NaN   8
    

    Here it uses the boolean condition and if true returns df['x'] else df['y']

提交回复
热议问题