Home > Back-end >  How can I reconstruct linear indices for a filtered 2D array?
How can I reconstruct linear indices for a filtered 2D array?

Time:08-03

Suppose I have the following numpy array

>>> arr = np.array([[0,1,0,1],
                    [0,0,0,1],
                    [1,0,1,0]])

where values of 0 indicate "valid" values and values of 1 indicate "invalid" values. Next, suppose that I filter out the invalid 1 values as follows:

>>> mask = arr == 1
>>> arr_filt = arr[~mask]
array([0, 0, 0, 0, 0, 0, 0])

If I want to go from a linear index of a valid value (0) in the original arr to the linear index of the same value in the new filtered arr_filt, I can proceed as follows:

# record the cumulative total number of invalid values
num_invalid_prev = np.cumsum(mask.flatten())

# example of going from the linear index of a valid value in the
# original array to the linear index of the same value in the
# filtered array
ij_idx = (0,2)
linear_idx_orig = np.ravel_multi_index(ij_idx,arr.shape)
linear_idx_filt = linear_idx_orig - num_invalid_prev[linear_idx_orig]

However, I'm interested in going the other way. That is, given the linear index of a valid value in the filtered arr_filt and the same num_invalid_prev array, can I get back the linear index of the same valid value in the unfiltered arr?

CodePudding user response:

You can use np.nonzero() to get indices:

ix = np.c_[np.nonzero(~mask)]
>>> ix
array([[0, 0],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2],
       [2, 1],
       [2, 3]])

Then, you can for example look up the index of the second valid value:

>>> tuple(ix[1])
(0, 2)

>>> arr[tuple(ix[1])]
0
  • Related