5

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.

7
  • 3
    x[-2] is valid right? Numpy supports negative indices. Would you like to override this feature? Commented Jun 7, 2019 at 11:58
  • 1
    This seems like something that scipy people would have to add to numpy. I don't think numpy has this option. You can though use try and except, if index not found, return np.nan or something like that. That's the only thing I can think of right now. Commented Jun 7, 2019 at 12:07
  • why don't you just try except Commented Jun 7, 2019 at 12:51
  • @J.Doe: cant. negative indices are valid in numpy Commented Jun 7, 2019 at 12:58
  • 1
    Ah I understand now, you want to disable negative indexing. In that case I think you need a wrapper, exactly like this answer and in __getitem__ you can then also check if the index is out of bounds manually or with a try/except. I don't think you can monkeypatch a np.ndarray. Commented Jun 7, 2019 at 13:21

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.