为什么numpy.logical_and在此示例中创建单个维度?

时间:2017-11-06 10:47:32

标签: python arrays numpy

我偶然发现了一些对我来说有点奇怪的事情。 请考虑以下代码:

import numpy as np

a = np.random.rand(6,7)
print(a.shape)

b = np.logical_and([a <= 1], [a >= 0])
print(b.shape)

虽然我可以用numpy.squeeze轻松摆脱b的单例维度,但我想知道为什么它甚至会出现。

根据文档here,它说:

  

返回:

     

y:ndarray或bool

Boolean result with the same shape as x1 and x2 of the logical AND operation on corresponding elements of x1 and x2

但是a和b的形状并不相同。我错过了什么?

1 个答案:

答案 0 :(得分:1)

因为在使用方括号将布尔数组放入列表时添加维度:

[a <= 1]

注意:

In [10]: np.array([a <= 1])
Out[10]:
array([[[ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True],
        [ True,  True,  True,  True,  True,  True,  True]]], dtype=bool)

In [11]: np.array([a <= 1]).shape
Out[11]: (1, 6, 7)

只需使用:

b = np.logical_and(a <= 1, a >= 0)