1

My question is similar to this one

Get value at list/array index or "None" if out of range in Python

but I want to use multidimensional numpy array.

Can this be done without checking the indexes beforehand?

data = np.ones((2,3,4))
idx1 = [0,1]
idx2 = [1,2]
idx3 = [0, 100]
data[idx1, idx2, idx3]

Desired output:

array([1., np.nan])
Hudler
  • 23
  • 3

1 Answers1

0

Given our data

import numpy as np    
data = np.ones((2,3,4))
idx = [[0,1], [1,2], [0, 100]]
shape = np.array(data.shape)

You can get any index column that extends past your original array using

invalids = np.any(idx > shape[:, None] - 1, axis=0)

and clip your indices to valid values using

valids = np.clip(idx, 0, shape[:, None] - 1)

these indicies can be used to index our array

out = data[valids.tolist()]

and the mask of invalid indices can be used to set outliers to nan

out[invalids] = np.nan
# array([ 1., nan])
Nils Werner
  • 34,832
  • 7
  • 76
  • 98