如何使用特定规则在Python中逐元素地比较两个数组?

use*_*839 1 python arrays compare numpy

比方说我有:

numpy.random.seed(20)
a=numpy.random.rand(5000)
b=numpy.random.rand(5000)
Run Code Online (Sandbox Code Playgroud)

我想获得一个位置的索引a[x] > b[x],即所有x的索引

此外,我想得到一个指数(a[x-1] < b[x-1]) && (a[x] > b[x]).

有人可以帮忙吗?我有一种感觉,我必须使用蒙面数组,但我不知道如何.

alk*_*lko 7

首先是直截了当的,使用numpy.where:

>>> numpy.where(a>b)
(array([   0,    1,    2, ..., 4993, 4994, 4999]),)
Run Code Online (Sandbox Code Playgroud)

对于第二个,你可以开始

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

但你必须分开处理角落案件.

再一次,@ askewchan得到了正确的表达式第二,而我没有正确添加1 :)

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