1

I have recently started working in numpy. I am trying to test if a 2d array contains a specific subarray. The code below returns an error. How can I fix this?

import numpy as np

testArray = np.array([[None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0]])

for i in range(len(testArray)):
    if (testArray[i] == [None, 0]):
        print(i)
Luke Schultz
  • 91
  • 1
  • 6

3 Answers3

1

Without iterating, you can use all:

>>> testArray[(testArray == [None,0]).all(1)]
array([[None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0],
       [None, 0]], dtype=object)

Or if you just want to see whether that subarray exists, use any in addition:

>>> (testArray == [None,0]).all(1).any()
True
sacuL
  • 49,704
  • 8
  • 81
  • 106
0

The error you are seeing is a Value Error. When you compare the numpy arrays, you get an array consisting of boolean values. The problem was that you were using that array to as your condition, which resulted in the value error since the truth-value of arrays is ambiguous. You can resolve by using .any or .all, depending on whether you care if all the elements are present in your array.

Try this:

testArray = np.array([[None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0]]) 

for i in range(len(testArray)): 
    containsValue = (testArray[i] == [None, 0]).all()
    if (containsValue): 
        print(i) 
genhernandez
  • 453
  • 1
  • 5
  • 19
0

Well, one of your '[None, 0]' is a list which you are comparing to an array which doesn't make much sense. So if you want to fix the code then you can access the values by:

import numpy as np

testArray = np.array([[None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0], [None, 0]])

for i in range(len(testArray)):
    if (testArray[i][0] == None and testArray[i][1] == 0):
        print(i)