如何对2D numpy数组的所有列进行逻辑运算 [英] How to operate logic operation of all columns of a 2D numpy array

查看:675
本文介绍了如何对2D numpy数组的所有列进行逻辑运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下由四个行和三个列组成的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆