Benny K
Benny K

Reputation: 2087

Column wise logical operation in numpy

What is the correct way to make logical operation between the columns of numpy array?

For now I found:

import numpy as np

x = np.random.randint(3, 10, (5, 4))
col_or = np.sum(x > 8, axis=1) != 0
col_and = np.prod(x > 8, axis=1) != 0

It bothers me that I need to convert the logical values to numeric values and the logical operations to regular arithmetic operations. In addition, I also need to check for inequality (!= 0)

Is there more appropriate way of doing this?

Upvotes: 1

Views: 630

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114320

You should probably be using np.all and np.any for your operations. Not only are they more efficient in terms of how the check is carried out, but they short-circuit.

I realize that this is just an example, but I would avoid recomputing the mask multiple times as well:

mask = x > 8
col_or = np.any(mask, axis=1)
col_and = np.all(mask, axis=1)

You can also use the all and any methods of the array itself:

col_or = mask.any(axis=1)
col_and = mask.all(axis=1)

Upvotes: 3

Related Questions