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

标签 python python-3.x pandas

我正在尝试创建一个标志变量(即一个具有二进制值的新列,例如 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

关于python - 使用 np.where 根据条件在 pandas df 中创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265766/

相关文章:

python - 生菜、 Django 的背景

python - 选择离 SVM 超车道最近的 5 个数据点

python - 移植pickle py2到py3 字符串变成字节

python - 我找不到将 Pandas 时间戳转换为 matplotlib 图日期的方法

python - DataFrame 中行之间的二元运算

python - Django 500 服务器错误仅出现在一个 URL 中

python - 如何在 OpenCV 3.0 或更高版本中使用estimateRigidTransform,还有其他选择吗?

python - Z3 更好的读取和解析 DIMACS 的方法

python - 统一码编码错误 : 'mbcs' codec can't encode characters in position 0--1: invalid character upon running a PyInstaller-compiled script

python - 将一年中的几周分开并计算数据框中的平均值