Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value when indexing outside of a numpy array, even with non-trivial indexing

Is it possible to look up entries from an nd array without throwing an IndexError?

I'm hoping for something like:

>>> a = np.arange(10) * 2
>>> a[[-4, 2, 8, 12]]
IndexError
>>> wrap(a, default=-1)[[-4, 2, 8, 12]]
[-1, 4, 16, -1]

>>> wrap(a, default=-1)[200]
-1

Or possibly more like get_with_default(a, [-4, 2, 8, 12], default=-1)

Is there some builtin way to do this? Can I ask numpy not to throw the exception and return garbage, which I can then replace with my default value?

like image 249
Eric Avatar asked Apr 28 '16 18:04

Eric


People also ask

What is NumPy array indexing?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Is negative indexing possible in NumPy array?

Single element indexing works exactly like that for other standard Python sequences. It is 0-based, and accepts negative indices for indexing from the end of the array.

How do you find the index of an element in an array NumPy?

Using ndenumerate() function to find the Index of value It is usually used to find the first occurrence of the element in the given numpy array.

What is NumPy array explain with the help of indexing and slicing operations?

Slicing arrays Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .


2 Answers

np.take with clip mode, sort of does this

In [155]: a
Out[155]: array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

In [156]: a.take([-4,2,8,12],mode='raise')
...
IndexError: index 12 is out of bounds for size 10

In [157]: a.take([-4,2,8,12],mode='wrap')
Out[157]: array([12,  4, 16,  4])

In [158]: a.take([-4,2,8,12],mode='clip')
Out[158]: array([ 0,  4, 16, 18])

Except you don't have much control over the return value - here indexing on 12 return 18, the last value. And treated the -4 as out of bounds in the other direction, returning 0.

One way of adding the defaults is to pad a first

In [174]: a = np.arange(10) * 2
In [175]: ind=np.array([-4,2,8,12])

In [176]: np.pad(a, [1,1], 'constant', constant_values=-1).take(ind+1, mode='clip')
Out[176]: array([-1,  4, 16, -1])

Not exactly pretty, but a start.

like image 196
hpaulj Avatar answered Nov 11 '22 04:11

hpaulj


This is my first post on any stack exchange site so forgive me for any stylistic errors (hopefully there are only stylistic errors). I am interested in the same feature but could not find anything from numpy better than np.take mentioned by hpaulj. Still np.take doesn't do exactly what's needed. Alfe's answer works but would need some elaboration in order to handle n-dimensional inputs. The following is another workaround that generalizes to the n-dimensional case. The basic idea is similar the one used by Alfe: create a new index with the out of bounds indices masked out (in my case) or disguised (in Alfe's case) and use it to index the input array without raising an error.

def take(a,indices,default=0):
    #initialize mask; will broadcast to length of indices[0] in first iteration
    mask = True
    for i,ind in enumerate(indices):
        #each element of the mask is only True if all indices at that position are in bounds 
        mask = mask & (0 <= ind) & (ind < a.shape[i])
    #create in_bound indices
    in_bound = [ind[mask] for ind in indices]
    #initialize result with default value
    result = default * np.ones(len(mask),dtype=a.dtype)
    #set elements indexed by in_bound to their appropriate values in a
    result[mask] = a[tuple(in_bound)]
    return result

And here is the output from Eric's sample problem:

>>> a = np.arange(10)*2
>>> indices = (np.array([-4,2,8,12]),)
>>> take(a,indices,default=-1)
array([-1,  4, 16, -1])
like image 43
jgoodman Avatar answered Nov 11 '22 02:11

jgoodman