5

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?

1
  • 3
    The documentation for np.less_equal (and the other comparison functions) says it returns "the truth value" of the comparison, so it may not be possible to do this without manually iterating over the array. Commented Jan 10, 2015 at 21:17

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The __le__ function that we're not allowed to see is operating in a plain old Python list comprehension not a numpy context. Therefore, np.less_equal is not called.
@msw lhs <= rhs is what the OP wanted to use, which calls np.less_than, I'm stating why it returns bool instead of the results of the comparisons as he expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.