简体   繁体   中英

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. I think I am overthinking this but I have tried the where function and intersection and cannot get it to work. My actual array is much longer but here two simple arrays to demonstrate what I want:

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

np.where converts a boolean mask like arr1 >= 0.01 into an index. You can select with the mask directly, but it won't be invertible. 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 :

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. Since index1 is the original index of each element in selection1 , index1[ind1] converts ind1 back into the arr1 reference frame.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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