Skip to content
Advertisement

Is there a 2-D “where” in numpy?

This might seem an odd question, but it boils down to quite a simple operation that I can’t find a numpy equivalent for. I’ve looked at np.where as well as many other operations but can’t find anything that does this:

a = np.array([1,2,3])
b = np.array([1,2,3,4])
c = np.array([i<b for i in a])

The output is a 2-D array (3,4), of booleans comparing each value.

Advertisement

Answer

If you’re asking how to get c without loop, try this

# make "a" a column vector
# > broadcasts to produce a len(a) x len(b) array
c = b > a[:, None]
c
array([[False,  True,  True,  True],
       [False, False,  True,  True],
       [False, False, False,  True]])
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement