kdbaseball8
kdbaseball8

Reputation: 111

check if value exists at index in numpy array

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!

Upvotes: 1

Views: 1206

Answers (2)

miraunpajaro
miraunpajaro

Reputation: 152

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

Upvotes: 1

hpaulj
hpaulj

Reputation: 231325

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

Upvotes: 1

Related Questions