【问题标题】:Pandas multiples conditions resulting in zerosPandas 多个条件导致零
【发布时间】:2022-11-16 02:44:43
【问题描述】:

在熊猫中评估以下条件时,熊猫条件语句导致“0”,不确定为什么结果未按要求打印。

Source:
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

用于此的代码是:

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

【问题讨论】:

  • 我认为您需要一个看起来像这样的附加条件 (df['t_type'].notnull) & (df['Att'].notnull()) & (df['Name'].notnull()) 和一个只是空字符串的附加值才能获得预期的结果。

标签: python pandas


【解决方案1】:

Numpy.select 有一个default 参数,你可以指定它为任何你想要的:

df['Remarks'] = np.select(conditions, values, np.NaN)

print(df)

输出:

  t_type   Att Name                         Remarks
0    ABC   NaN   A1                     Att is Null
1    CCC  A_XY  NaN                    Name is Null
2    ABC   NaN  NaN      ABC - Att and Name is Null
3    CDE   NaN  NaN  Non ABC - Att and Name is Null
4    CDE  A_ZZ   A2                             nan
5    ABC  A_DD   A4                             nan

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2015-12-11
    • 2021-12-21
    • 2021-09-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多