How do I compare two arrays element-wise in Python using specific rules?

arrays, compare, numpy, python

Solution

First is straightforward, use `numpy.where`:

>>> numpy.where(a>b)
(array([   0,    1,    2, ..., 4993, 4994, 4999]),)

For second one you can start with

>>> np.where((a>b) & (np.roll(a, 1) < np.roll(b, 1)))
(array([   5,    9,   17, ..., 4988, 4991, 4999]),)

but you have to treat corner cases separately.

Once again, @askewchan came with correct expression for second, while I failed to add 1 properly :)

>>> np.where((a[1:] > b[1:]) & (a[:-1] < b[:-1]))[0] + 1
array([   5,    9,   17, ..., 4988, 4991, 4999])

Problem

Let's say I have: ``` numpy.random.seed(20) a=numpy.random.rand(5000) b=numpy.random.rand(5000) ``` I want to get the indices of a where `a[x] > b[x]`, i.e. all x's Furthermore, I want to get the indices of a where `(a[x-1] < b[x-1]) && (a[x] > b[x])`. Can someone please help? I've got a feeling I have to use masked arrays, but I can't quite figure out how.

Original source