我有两个包含对象的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 <= rhs
给了我很多傻瓜 有没有一种方法result
可以在__le__
不编写python循环的情况下获取方法调用结果的数组?
Numpy的Github页面上ndarray
指出比较运算符等效于Numpy中的ufunc形式。因此lhs <= 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数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句