【问题标题】:numpy elementwise comparison with overloaded operatornumpy elementwise 与重载运算符的比较
【发布时间】:2015-01-10 20:51:01
【问题描述】:

我有两个 numpy 数组,其中包含带有重载比较运算符的对象,该运算符返回另一个对象,而不是 True 或 False。如何创建包含单个比较结果的数组。我希望结果是一个对象数组,如下所示

lhs = ... # np.array of objects with __le__ overloaded
rhs = ... # another np.array
result = np.array([l <= r for l, r in izip(lhs, rhs)])

但是lhs &lt;= rhs 给了我一个布尔数组。 有没有办法让result 成为__le__ 方法调用结果的数组,而无需编写python 循环?

【问题讨论】:

  • documentation for np.less_equal(和其他比较函数)表示它返回比较的“真值”,因此如果不手动迭代数组可能无法做到这一点.

标签: python numpy operator-overloading


【解决方案1】:
ndarray 上的

Numpy's Github page 声明比较运算符等效于 Numpy 中的 ufunc 形式。因此lhs &lt;= rhs 等价于np.less_equal(lhs, rhs)

来自np.info(np.less_equal)的输出

 Returns
 ------- out : bool or ndarray of bool
   Array of bools, or a single bool if `x1` and `x2` are scalars.

要解决这个问题,您可以使用:

import operator
result = np.vectorize(operator.le)(lhs, rhs)

np.vectorize 也允许您在比较中使用 Numpy 的广播。它将使用您的对象比较,并以与您的列表理解相同的形式返回这些比较结果的 numpy 数组。

【讨论】:

  • 我们不允许看到的 __le__ 函数在普通的旧 Python 列表理解而不是 numpy 上下文中运行。因此,不调用 np.less_equal。
  • @msw lhs &lt;= rhs 是 OP 想要使用的,它调用 np.less_than,我在说明为什么它返回 bool 而不是他预期的比较结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
相关资源
最近更新 更多