Skip to main content
 首页 » 编程设计

python之使用 np.where 根据条件在 pandas df 中创建一个新列

2025年01月19日10wuhuacong

我正在尝试创建一个标志变量(即一个具有二进制值的新列,例如 1 表示 True,0 表示 False)- 我已经尝试了 np.where(as per this post ) 和 df.where 无济于事。

与 df.where 使用:

df.where(((df['MOSL_Rating'] == 'Highly Effective') & (df['MOTP_Rating'] == 'Developing')) | ((df['MOSL_Rating'] == 'Highly Effective') & (df['MOTP_Rating'] == 'Ineffective')) | ((df['MOSL_Rating'] == 'Effective') & (df['MOTP_Rating'] == 'Ineffective')) | ((df['MOSL_Rating'] == 'Ineffective') & (df['MOTP_Rating'] == 'Highly Effective')) | ((df['MOSL_Rating'] == 'Ineffective') & (df['MOTP_Rating'] == 'Effective')) | ((df['MOSL_Rating'] == 'Developing') & (df['MOTP_Rating'] == 'Highly Effective')), df['disp_rating'], 1, axis=1) 

但是这会返回 ValueError: For argument "inplace"expected type bool, received type int.

如果我将代码从 df['disp_rating'], 1, axis=1 更改为 df['disp_rating'], True, axis=1 它返回TypeError: 无法对具有非 np.nan 值的混合类型进行就地 bool 值设置

我也试过 np.where 但返回 ValueError: either both or neither of x and y should be given

我也读过 this question , 这看起来很相似。但是,当我使用那里提供的解决方案时,它会返回: KeyError: 'disp_rating'

如果我提前创建变量(以避免 Key Error),我只会收到另一个关于其他事情的错误。

我认为根据一些基本条件创建一个新变量会非常简单,但我已经坚持了一段时间,尽管阅读了文档和大量 SO 帖子,但我并没有真正取得任何进展。

编辑:为了更加清楚,我正在尝试根据同一 df 中其他 2 个列('MOSL_Rating 和'MOTP_Rating')中的值是否满足来创建一个新列(名为'disp_rating')一定条件下。我只有 1 个数据帧,所以我不想比较 2 个数据帧。 在 SQL 中我会使用 CASE WHEN 语句,在 SAS 中我会使用 IF/THEN/ELSE 语句。

我的 df 通常是这样的:

ID  Loc  MOSL_rating MOTP_Rating 
12  54X  D           E    
45  86I  D           I     
98  65R  H           H   

请您参考如下方法:

您的逻辑过于复杂,可以通过set 进行简化/优化。下面是一个演示。

d = {frozenset({'H', 'D'}), 
     frozenset({'H', 'I'}), 
     frozenset({'E', 'I'})} 
 
df['MOSL_MOTP'] = list(map(frozenset, zip(df['MOSL_Rating'], df['MOTP_Rating']))) 
df['Result'] = np.where(df['MOSL_MOTP'].isin(d), 1, 0) 
 
#    ID  Loc MOSL_Rating MOTP_Rating MOSL_MOTP  Result 
# 0  12  54X           D           E    (E, D)       0 
# 1  45  86I           D           I    (D, I)       0 
# 2  98  65R           H           H       (H)       0 
# 3  95  66R           H           D    (D, H)       1 
# 4  96  67R           D           H    (D, H)       1 
# 5  97  68R           E           I    (E, I)       1