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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With