Skip to main content
 首页 » 编程设计

python之如何使用特定规则在 Python 中按元素比较两个数组

2025年05月04日14java哥

假设我有:

numpy.random.seed(20) 
a=numpy.random.rand(5000) 
b=numpy.random.rand(5000) 

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

此外,我想获得一个 where (a[x-1] < b[x-1]) && (a[x] > b[x]) 的索引.

有人可以帮忙吗?我觉得我必须使用掩码数组,但我不太清楚如何使用。

请您参考如下方法:

首先很简单,使用numpy.where:

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

你可以从第二个开始

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

但是你必须单独处理极端情况。

再一次,@askewchan 给出了 second 的正确表达式,而我没能正确地加 1 :)

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