Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy elementwise comparison with overloaded operator

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?

like image 560
David Nehme Avatar asked Oct 19 '22 19:10

David Nehme


1 Answers

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.

like image 113
ryanpattison Avatar answered Nov 03 '22 02:11

ryanpattison