Tim4497
Tim4497

Reputation: 380

Matrix contains specific number per row

I want to know if there is at least one zero in each row of a matrix

i = 0
for row in range(rows):
    if A[row].contains(0):
        i += 1

i == rows

is this right or is there a better way?

Upvotes: 1

Views: 107

Answers (1)

tel
tel

Reputation: 13999

You can reproduce the effect of your whole code block in a single vectorized operation:

np.all((rows == 0).sum(axis=1))

Alternatively (building off of Mateen Ulhaq's suggestion in the comments), you could do:

np.all(np.any(rows == 0, axis=1))

Testing it out

a = np.arange(5*5).reshape(5,5)
b = a.copy()
b[:, 3] = 0

print('a\n%s\n' % a)
print('b\n%s\n' % b)

print('method 1')
print(np.all((a == 0).sum(axis=1)))
print(np.all((b == 0).sum(axis=1)))
print()

print('method 2')
print(np.all(np.any(a == 0, axis=1)))
print(np.all(np.any(b == 0, axis=1)))

Output:

a
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

b
[[ 0  1  2  0  4]
 [ 5  6  7  0  9]
 [10 11 12  0 14]
 [15 16 17  0 19]
 [20 21 22  0 24]]

method 1
False
True

method 2
False
True

Timings

%%timeit
np.all((a == 0).sum(axis=1))
8.73 µs ± 56.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%%timeit
np.all(np.any(a == 0, axis=1))
7.87 µs ± 54 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

So the second method (which uses np.any) is slightly faster.

Upvotes: 2

Related Questions