首页 > 解决方案 > 为什么选择numpy数组元素时不能使用AND运算符?

问题描述

我正在尝试这样做:

X = U[(U > lims[0] & U < lims[1])]  #U is numpy array

输出:

Traceback (most recent call last):
  File "Ha.py", line 19, in <module>
    X = U[(U > lims[0] & U < lims[1])]
TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

 X = U[(U > lims[0])

完美运行。

怎么了?我怎样才能优雅地克服这一点?

标签: pythonnumpy

解决方案


当您尝试以下操作时:

X = U[(U > lims[0] & U < lims[1])] 

Numpy 认为您正在尝试执行按位运算。这是因为按位&运算的优先级高于条件>运算。

您应该尝试以下方法:

X = U[(U > lims[0]) & (U < lims[1])]

推荐阅读