Python NumPy 数组中满足值和索引条件的元素的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25438420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:12:45  来源:igfitidea点击:

Indexes of elements in NumPy array that satisfy conditions on the value and the index

pythonnumpy

提问by user3329302

I have a NumPy array, A. I want to know the indexes of the elements in A equal to a value and which indexes satisfy some condition:

我有一个 NumPy 数组,A. 我想知道 A 中元素的索引等于一个值以及哪些索引满足某些条件:

import numpy as np
A = np.array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])

value = 2
ind = np.array([0, 1, 5, 10])  # Index belongs to ind

Here is what I did:

这是我所做的:

B = np.where(A==value)[0]  # Gives the indexes in A for which value = 2
print(B)

[1 5 9]

mask = np.in1d(B, ind)  # Gives the index values that belong to the ind array
print(mask)
array([ True, True, False], dtype=bool)

print B[mask]  # Is the solution
[1 5]

The solution works, but I find it complicated. Also, in1ddoes a sort which is slow. Is there a better way of achieving this?

该解决方案有效,但我觉得它很复杂。此外,in1d做一个很慢的排序。有没有更好的方法来实现这一目标?

采纳答案by Robb

If you flip the operation order around you can do it in one line:

如果您翻转操作顺序,您可以在一行中完成:

B = ind[A[ind]==value]
print B
[1 5]

Breaking that down:

打破它:

#subselect first
print A[ind]
[1 2 2 3]

#create a mask for the indices
print A[ind]==value
[False  True  True False]

print ind
[ 0  1  5 10]

print ind[A[ind]==value]
[1 5]

回答by Paul

The second two steps can be replaced by intersect1D. Probably also does a sort. Don't know how you'd avoid that unless you can guarantee your ind array is ordered.

后两步可以用intersect1D代替。大概也做了一个排序。不知道如何避免这种情况,除非您可以保证您的 ind 数组是有序的。

回答by John Zwinck

B = np.where(A==value)[0]  #gives the indexes in A for which value = 2
print np.intersect1d(B, ind)
[1 5]

回答by Praveen

How about deferring the np.whereuntil the end, like so:

推迟np.where到最后怎么样,像这样:

res = (A == value)
mask = np.zeros(A.size)
mask[ind] = 1
print np.where(res * z)[0]

That shouldn't require any sorting.

那应该不需要任何排序。

回答by wwii

This is a bit different - I didn't do any timing tests.

这有点不同 - 我没有做任何计时测试。

>>> 
>>> A = np.array([1,2,3,4,1,2,3,4,1,2,3,4])
>>> ind = np.array([0,1,5,10])
>>> b = np.ix_(A==2)
>>> np.intersect1d(ind, *b)
array([1, 5])
>>> 

Although after looking at @Robb's solution, that's probably the way to do it.

尽管在查看了@Robb 的解决方案之后,这可能就是这样做的方法。