Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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.

like image 415
blue_note Avatar asked Nov 16 '22 07:11

blue_note


1 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.

like image 180
hpaulj Avatar answered Dec 22 '22 01:12

hpaulj