首页 > 解决方案 > 比较并选择第一个非空列值 Python Dataframe

问题描述

只比较 3 列,homePhone、workPhone、CellPhone、

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

使用 Python 熊猫

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

标签: pythonpandasdataframe

解决方案


如果此事确实只涉及三列,则可以使用np.whereNumPy 中的:

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)

推荐阅读