如何对2D numpy数组的所有列进行逻辑运算 [英] How to operate logic operation of all columns of a 2D numpy array
问题描述
假设我有以下由四个行和三个列组成的2D
NumPy
数组:
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)
生成包含逻辑或所有列(例如[True, False]
)的1D
数组的有效方法是什么?
What would be an efficient way to generate a 1D
array that contains the logic or of all columns (like [True, False]
)?
我在网上搜索,发现有人引用sum(axis=)
来计算sum
.
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?
推荐答案
是的.使用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)
请注意当您将参数axis
更改为1
时会发生什么:
Note what happens when you change the argument axis
to 1
:
>>> a.any(axis=1)
array([ True, False, True], dtype=bool)
>>>
如果您要逻辑-并使用all
:
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)
>>>
还请注意,如果省略axis
关键字参数,则它适用于所有元素:
Also note that if you leave out the axis
keyword argument, it works across every element:
>>> a.any()
True
>>> a.all()
False
这篇关于如何对2D numpy数组的所有列进行逻辑运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!