比较并选择第一个非空列值Python Dataframe

时间:2018-05-24 01:06:07

标签: python pandas dataframe

仅比较3列,homePhone,workPhone,CellPhone,

如何在“我想要”列中选择第一个非空列值

使用Python Pandas

    name    homePhone   workPhone   CellPhone   I want
1   Tom        888        666         null       888
2   John      null        777        null       777
3   Lily      null       null       333         333

1 个答案:

答案 0 :(得分:-1)

如果问题确实只涉及三列,您可以使用NumPy中的np.where

import numpy as np  
df['I want'] = np.where(df['homePhone'].isnull(), 
                        np.where(df['workPhone'].isnull(), 
                                 df['CellPhone'], 
                                 df['workPhone']), 
                        df['homePhone']).astype(int)