【问题标题】:confusion with the use of and operator与和运算符的使用混淆
【发布时间】:2020-10-14 13:35:28
【问题描述】:

以下是我的数据框的简化版本

df = pd.DataFrame(np.random.randint(1,10,(5,2)),columns=['x','y'])

如果 x 和 y 值均 > 5,则新列 'z' 的值将为 0,否则为 1

df[z] = np.where(ddd.x>5 and ddd.y>5,0,1)

但是,我得到了这个错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

即使我使用也一样

df[z] = np.where(ddd.x>5 & ddd.y>5,0,1)

我错过了什么?

【问题讨论】:

  • 用括号分隔谓词:np.where((ddd.x > 5) & (ddd.y > 5), 0, 1)
  • 变量z的值是多少?

标签: python pandas numpy operator-keyword


【解决方案1】:

您需要为每个条件使用括号,否则它将不起作用:

df[z] = np.where((ddd.x > 5) & (ddd.y > 5), 0, 1)

【讨论】:

    【解决方案2】:

    您只需要为每个条件添加括号。看看这个:

    df[z] = np.where((ddd.x>5) & (ddd.y>5,0,1))
    

    【讨论】:

      猜你喜欢
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多