3sm1r
3sm1r

Reputation: 530

function `any()` applied to several arrays rather than just one

I want to apply the function any() to all the rows of a matrix at the same time.

If I use any() with a vector, of course it will return True (or 1 in my case) whenever any element would return True:

import numpy as np

print any(np.array([0,0,0,1]))*1

Now suppose I have a matrix instead. If I want to obtain a vector with 1 and 0 depending on whether each element of the matrix would return True when taken alone, I can do it with a for loop:

matrix=np.array([[0,0,0],[0,0,1],[0,1,0]])
result=np.zeros(len(matrix)).astype('int')
i=0
for line in matrix:
    result[i]=any(matrix[i])
    i+=1
    

print result

However, this method does not seem very practical, because the elements of the matrix will be handled once at a time with the for loop. Is there a better way to extend any to a matrix input, in such a way that it returns a vector of several 1 and 0 as above?

Note that I do not want to use matrix.any() because it will just return a single True or False statement, whereas I want it to be applied to each individual element of the matrix.

Upvotes: 1

Views: 46

Answers (2)

Mario Ishac
Mario Ishac

Reputation: 5907

You can do this:

import numpy as np

matrix = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]])
matrix_sums = np.sum(matrix, axis=1)
are_truthy_matrix_sums = matrix_sums > 0

print are_truthy_matrix_sums

We use np.sum to simplify the matrix to a 1D array with the sums, before comparing these sums against 0 to see if there were any truthy values in these rows.

This prints:

[False  True  True]

Upvotes: 1

user2357112
user2357112

Reputation: 281683

numpy.any(matrix, axis=1)

numpy.any already has the functionality you want.

Upvotes: 1

Related Questions