SteveTz
SteveTz

Reputation: 242

set Numpy logical_or to return 1 for True and 0 for false

I want to sum the result of the np.logical_or but it returns True and False how can I change it so that I can get numeric values

import numpy as np
a = [[0, 1, 2],
    [3, 4, 5]]
b = [[0,7,8],
    [9,10,11]]
np.logical_or(a,b)

#output:
#array([[False,  True,  True],
#       [ True,  True,  True]])
#I can not sum it

Upvotes: 0

Views: 718

Answers (1)

Pietro
Pietro

Reputation: 1110

You can cast the result of the logical or to int and sum that:

import numpy as np

a = [[0, 1, 2], [3, 4, 5]]
b = [[0, 7, 8], [9, 10, 11]]
lor = np.logical_or(a, b)
print(f"lor {lor}")
print(f"lor.dtype {lor.dtype}")

sum_lor = np.sum(lor.astype(np.int))

print(f"sum_lor {sum_lor}")
print(f"sum_lor.dtype {sum_lor.dtype}")

Which prints:

lor [[False  True  True]
    [ True  True  True]]
lor.dtype bool
sum_lor 5
sum_lor.dtype int64

Upvotes: 1

Related Questions