Search code examples
pythonarraysnumpyany

any does not work properly with 1D array


I have a simple numpy 2D Array. E.g. :

M=np.array([[15,1,0],
            [19,5,2]])

which I loop over to check if in each line (axis 1) a value exist greater than e.g. 2. As the first value is always greater than 2, I slice the array to only check which of the other n values in that line is greater than 2.

#A    
for i in range(len(M)):
          if any(M[i,1:])>=2:
              disp('Super')

Or, as I am not so familiar with python yet, I also used this code, which should function the same, right?

#B    
for i in range(len(M)):
          if any(x>=2 in x in M[i,1:]):
              disp('Great')

The Problem I have now is that the any does not care about my slicing (M[i,1:]). It checks always the total array and of course finding a value greater than 2. I expected in the first itteration a FALSE and in the second a TRUE


Solution

  • any(l) takes a list (or iterable) of values and returns True if any of the values it iterated over are truthy i.e. bool(value) == True. Therefore, it doesn't make sense to compare the output of any(...) with a number so I wouldn't do any(M[i,1:])>=2.

    However, you can do any(M[i, 1:] > 2) where M[i, 1:] > 2 broadcasts the greater than operator to each value of the given row and returns you a boolean array that any can operate over.