modify numpy array to return `nan` out of bounds?

Viewed 628

Is there anyway to create a numpy array that returns np.nan when indexed out of bounds? Eg

x = np.array([1,2,3])
x[1] # 2
x[-2] # np.nan
x[5] # np.nan

The closest thing I found was np.pad.

I know I could write a wrapper class, but I was wondering if there's any efficient numpy way to do it.

2 Answers
In [360]: x = np.array([1,2,3])                                                                        
In [361]: x[1]                                                                                         
Out[361]: 2

np.take lets you index with mode control. The default is to raise an error if the index is out of bounds (see the docs for other options):

In [363]: np.take(x,1)                                                                                 
Out[363]: 2
In [364]: np.take(x,-2)                                                                                
Out[364]: 2
In [365]: np.take(x,5)                                                                                 
----
IndexError: index 5 is out of bounds for size 3

You could write a little function that wraps this in a try/except, returning np.nan in case of IndexError.

Keep in mind that np.nan is a float, while your example array is integer dtype.

You have many choices:

  • Just insert a try/except in your code.
  • Create a class that inherit from np.array and redefine the indexing operator to implement the behavior
  • write a simple function that does the try/except

I like the class one.

Related