[英]How to get elements and indices into original array with mask
I am trying to get both the elements and indices from two arrays where the elements match.我试图从元素匹配的两个 arrays 中获取元素和索引。 I think I am overthinking this but I have tried the
where
function and intersection and cannot get it to work.我想我想多了,但我已经尝试了 function 和交叉点的
where
,但无法让它工作。 My actual array is much longer but here two simple arrays to demonstrate what I want:我的实际数组要长得多,但这里有两个简单的 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))
Printing ind
shows array([1, 2, 3, 4])
.打印
ind
显示array([1, 2, 3, 4])
。 Technically, I want the elements 1, 2, 3, 4
from arr1
and elements 0, 1, 2, 3
from arr2
, which gives the elements 0.016, 0.033, 0.050, 0.067
, which match in both arrays.从技术上讲,我想要
arr1
中的元素1, 2, 3, 4
和arr2
中的元素0, 1, 2, 3
这给出了元素0.016, 0.033, 0.050, 0.067
,它们在 arrays 中都匹配。
np.where
converts a boolean mask like arr1 >= 0.01
into an index. np.where
将 boolean 掩码(如arr1 >= 0.01
)转换为索引。 You can select with the mask directly, but it won't be invertible.您可以直接使用掩码 select,但它不会可逆。 You need to invert the indices because you want to intersect from the original array, not the selection.
您需要反转索引,因为您想与原始数组相交,而不是选择。 Make sure to set
return_indices=True
to get indices from intersect1d
:确保设置
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]
While you get elements
directly from the intersection, the indices ind1
and ind2
are referencing the masked selections.当您直接从交叉点获取
elements
时,索引ind1
和ind2
正在引用被屏蔽的选择。 Since index1
is the original index of each element in selection1
, index1[ind1]
converts ind1
back into the arr1
reference frame.由于
index1
是selection1
中每个元素的原始索引, index1[ind1]
将ind1
转换回arr1
参考帧。
Your original expression was actually meaningless.你原来的表达其实是没有意义的。 You were intersecting the indices in each array that met your condition.
您正在与满足您条件的每个数组中的索引相交。 That has nothing to do with the values at those indices (which wouldn't have to match at all).
这与那些索引处的值无关(根本不必匹配)。 The seemingly correct result is purely a coincidence based on a fortuitous array construction.
看似正确的结果纯属巧合,基于偶然的数组构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.