noodles guo
noodles guo

Reputation: 479

How to operate logic operation of all columns of a 2D numpy array

Let's say I have the following 2D NumPy array consisting of four rows and three columns:

>>> a = numpy.array([[True, False],[False, False], [True, False]])
>>> array([[ True, False],
       [False, False],
       [ True, False]], dtype=bool)

What would be an efficient way to generate a 1D array that contains the logic or of all columns (like [True, False])?

I searched the web and found someone referring to sum(axis=) to calculate the sum.

I wonder if there is some similar way for logic operation?

Upvotes: 24

Views: 9349

Answers (2)

Georgy
Georgy

Reputation: 13717

NumPy has also a reduce function which is similar to Python's reduce. It's possible to use it with NumPy's logical operations. For example:

>>> a = np.array([[True, False],[False, False], [True, False]])
>>> a
array([[ True, False],
       [False, False],
       [ True, False]])
>>> np.logical_or.reduce(a)
array([ True, False])
>>> np.logical_and.reduce(a)
array([False, False])

It also has the axis parameter:

>>> np.logical_or.reduce(a, axis=1)
array([ True, False,  True])
>>> np.logical_and.reduce(a, axis=1)
array([False, False, False])

The idea of reduce is that it cumulatively applies a function (in our case logical_or or logical_and) to each row or column.

Upvotes: 6

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95993

Yes, there is. Use any:

>>> a = np.array([[True, False],[False, False], [True, False]])
>>> a
array([[ True, False],
       [False, False],
       [ True, False]], dtype=bool)
>>> a.any(axis=0)
array([ True, False], dtype=bool)

Note what happens when you change the argument axis to 1:

>>> a.any(axis=1)
array([ True, False,  True], dtype=bool)
>>> 

If you want logical-and use all:

>>> b.all(axis=0)
array([False, False], dtype=bool)
>>> b.all(axis=1)
array([ True, False, False], dtype=bool)
>>> 

Also note that if you leave out the axis keyword argument, it works across every element:

>>> a.any()
True
>>> a.all()
False

Upvotes: 29

Related Questions