I have two numpy arrays containing objects with an overloaded comparison operator that returns another object, instead of True or False. How can I create an array containing the results of the individual comparisons. I would like result to be an array of objects like in the following
lhs = ... # np.array of objects with __le__ overloaded
rhs = ... # another np.array
result = np.array([l <= r for l, r in izip(lhs, rhs)])
but lhs <= rhs
gives me an array of bools.
Is there a way to get to the result
to be the array of the results of the __le__
method calls without writing a python loop?
Numpy's Github page on ndarray
states that the comparison operators are equivalent to the ufunc forms in Numpy. Therefore lhs <= rhs
is equivalent to np.less_equal(lhs, rhs)
From the output of 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.
To get around this you can use:
import operator
result = np.vectorize(operator.le)(lhs, rhs)
The np.vectorize
will allow you to use Numpy's broadcasting in the comparisons too. It will use your objects comparison and will return a numpy array of the results of those comparisons in the same form as your list comprehension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With