[英]Get indices of last N elements in each column of array A, but only those that are False in some mask M with same shape as A
[英]How to get elements and indices into original array with mask
我试图从元素匹配的两个 arrays 中获取元素和索引。 我想我想多了,但我已经尝试了 function 和交叉点的where
,但无法让它工作。 我的实际数组要长得多,但这里有两个简单的 arrays 来演示我想要的:
import numpy as np
arr1 = np.array([0.00, 0.016, 0.033, 0.050, 0.067])
arr2 = np.array([0.016, 0.033, 0.050, 0.067, 0.083])
ind = np.intersect1d(np.where(arr1 >= 0.01), np.where(arr2 >= 0.01))
打印ind
显示array([1, 2, 3, 4])
。 从技术上讲,我想要arr1
中的元素1, 2, 3, 4
和arr2
中的元素0, 1, 2, 3
这给出了元素0.016, 0.033, 0.050, 0.067
,它们在 arrays 中都匹配。
np.where
将 boolean 掩码(如arr1 >= 0.01
)转换为索引。 您可以直接使用掩码 select,但它不会可逆。 您需要反转索引,因为您想与原始数组相交,而不是选择。 确保设置return_indices=True
从intersect1d
获取索引:
index1 = np.nonzero(arr1 >= 0.01)
index2 = np.nonzero(arr2 >= 0.01)
selection1 = arr1[index1]
selection2 = arr2[index1]
elements, ind1, ind2 = np.intersect1d(selection1, selection2, return_indices=True)
index1 = index1[ind1]
index2 = index2[ind2]
当您直接从交叉点获取elements
时,索引ind1
和ind2
正在引用被屏蔽的选择。 由于index1
是selection1
中每个元素的原始索引, index1[ind1]
将ind1
转换回arr1
参考帧。
你原来的表达其实是没有意义的。 您正在与满足您条件的每个数组中的索引相交。 这与那些索引处的值无关(根本不必匹配)。 看似正确的结果纯属巧合,基于偶然的数组构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.