python - 如何对一个二维numpy数组的所有列进行逻辑运算

标签 python numpy

假设我有以下 2D NumPy 数组,由四行三列组成:

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

生成包含逻辑或所有列(如 [True, False])的 1D 数组的有效方法是什么?

我在网上搜索了一下,发现有人引用sum(axis=)来计算sum

不知道有没有类似的逻辑运算方式?

最佳答案

是的,有。使用任何:

>>> 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 时会发生什么:

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

如果你想要逻辑和使用all:

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

另请注意,如果您省略 axis 关键字参数,它适用于每个元素:

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

关于python - 如何对一个二维numpy数组的所有列进行逻辑运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40927057/

相关文章:

python - GLM R 与 Python

python - 有效地交叉两个 NumPy 数组

python - cv2.fitLine() 方法抛出的奇怪错误

python - Numpy/Python 与 Matlab 相比表现糟糕

python - Numpy:对行求和

python - 我如何使用 gevent 创建类似 "Omegle"的随机聊天?

python - 启用 selenium python 后找到并单击按钮

python - 在 Python : sqlalchemy. exc.programminingerror 语法错误处或附近执行原始 SQL 查询时出现问题

python - 字典排序和删除

python - 如何跟踪 "calling chain"从 numpy 到 C 的实现?