簡體   English   中英

NumPy數組中滿足值和索引條件的元素索引

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

我有一個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

這是我做的:

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]

解決方案有效,但我發現它很復雜。 另外, in1d做的很慢。 有沒有更好的方法來實現這一目標?

如果您翻轉操作順序,可以在一行中執行:

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

打破這種情況:

#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]
B = np.where(A==value)[0]  #gives the indexes in A for which value = 2
print np.intersect1d(B, ind)
[1 5]

后兩個步驟可以用intersect1D替換。 可能也做了一種。 除非你能保證你的ind陣列是有序的,否則你不知道如何避免這種情況。

如何將np.where推遲到最后,如下:

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

這不應該要求任何排序。

這有點不同 - 我沒有做任何計時測試。

>>> 
>>> 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])
>>> 

雖然在查看@ Robb的解決方案后,這可能就是這樣做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM