Pandas多条件判断返回0值,不符合预期输出问题求助
Pandas多条件判断返回0的问题解决
问题场景
执行Pandas多条件判断时,结果中出现了预期外的0值,无法得到目标输出。
源数据
t_type Att Name ABC NaN A1 CCC A_XY NaN ABC NaN NaN CDE NaN NaN CDE A_ZZ A2 ABC A_DD A4
使用代码
import pandas as pd import numpy as np df = pd.DataFrame({ 't_type': ['ABC', 'CCC', 'ABC', 'CDE', 'CDE', 'ABC'], 'Att': [np.nan, 'A_XY', np.nan, np.nan, 'A_ZZ', 'A_DD'], 'Name': ['A1', np.nan, np.nan, np.nan, 'A2', 'A4'] }) conditions = [ (df['t_type'] == 'ABC') & (df['Att'].isnull()) & (df['Name'].notnull()), (df['t_type'] != 'ABC') & (df['Att'].notnull()) & (df['Name'].isnull()), (df['t_type'] == 'ABC') & (df['Att'].isnull()) & (df['Name'].isnull()), (df['t_type'] != 'ABC') & (df['Att'].isnull()) & (df['Name'].isnull()) ] values = ['Att is Null','Name is Null','ABC - Att and Name is Null','Non ABC - Att and Name is Null'] df['Remarks'] = np.select(conditions, values) print(df.to_string())
预期输出
t_type Att Name Remarks ABC NaN A1 Att is Null CCC A_XY NaN Name is Null ABC NaN NaN ABC Att and Name is Null CDE NaN NaN Non ABC Att and Name is Null CDE A_ZZ A2 ABC A_DD A4
问题原因
np.select函数在没有任何条件匹配时,默认返回0。你的最后两行数据:
CDE A_ZZ A2:Att和Name都不为空,不满足任何给定的conditionsABC A_DD A4:Att不为空,Name也不为空,同样不满足任何conditions
所以这两行的Remarks被填充了默认值0,导致不符合预期。
解决方法
给np.select添加default参数,指定无匹配时的填充值(比如空字符串):
修改后的代码片段:
df['Remarks'] = np.select(conditions, values, default='')
执行后就能得到你想要的结果,无匹配条件的行Remarks会显示为空,而不是0。
内容的提问来源于stack exchange,提问作者kmr
相关产品推荐
相关产品推荐

