gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:48:13 26 4
gpt4 key购买 nike

假设我有以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com