1

This is probably an easy question but I can't seem to find the answer anywhere.

Let's say I have a numpy array like below:

x = np.array([[2,3],[1,0],[5,6]])

I am looking for a way to say if a value exists in x do something.

For example

if x[2][1] exists do something: This happens because it exists (and has a 6 value)

if x[4][2] exists do something: This does not happen because it does not exist (but does not throw an error)

Thank You!

2 Answers 2

1

Just use x.shape(). This returns a tuple with the dimensions, so in your example, you only need to check if 4<x.shape()[0] and 2<x.shape()[1].

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

Comments

1
In [114]: x = np.array([[2,3],[1,0],[5,6]])
In [115]: x[2][1]
Out[115]: 6
In [116]: x[2,1]                # more idiomatic indexing
Out[116]: 6

Indexing out of bounds does raise an error:

In [117]: x[4][2]
Traceback (most recent call last):
  File "<ipython-input-117-74efee77abf6>", line 1, in <module>
    x[4][2]
IndexError: index 4 is out of bounds for axis 0 with size 3

In [118]: x[4,2]
Traceback (most recent call last):
  File "<ipython-input-118-97c89dcf326d>", line 1, in <module>
    x[4,2]
IndexError: index 4 is out of bounds for axis 0 with size 3

3 Comments

I know the shape of my array it is 28x28. What I actually trying to do is write a blurring function that takes the average of the 8 digits around it and itself. The problem is the edges do not have 8 digits around them so I need something that accounts for this.
I was trying to write two loops where if the value index didn't exist it would just skip it.
If you are indexing with slices, you can end up with an 'empty' window, e.g. arr[26:29, 28:32]. That is you can 'slice' off the edge without warning (that's true for Python lists as well). Sounds like this is a bigger task, one involving convolving and other image processing. If numpy doesn't have the tools, you may want to look in scipy or other sci-kit.

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.