简体   繁体   English

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

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

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] , ie all x's 我想得到a[x] > b[x]的索引,即所有x

Furthermore, I want to get the indices of a where (a[x-1] < b[x-1]) && (a[x] > b[x]) . 此外,我想获得a (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. 我有一种必须使用遮罩数组的感觉,但是我不太清楚该怎么做。

First is straightforward, use numpy.where : 首先很简单,使用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 :) 再一次,@ askewchan附带正确的表达式第二秒钟,而我未能正确添加1 :)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM