简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM