为什么会这样numpy.u和在本例中创建一个单例维度?

2024-04-23 15:50:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

import numpy as np

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

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

而我可以很容易地去掉b的单子维数努比。挤压,我想知道为什么它会出现。你知道吗

根据文档here它说:

Returns:

y : ndarray or 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的形状不一样。我错过了什么?你知道吗


Tags: andofthe代码importnumpyasnp
1条回答
网友
1楼 · 发布于 2024-04-23 15:50:18

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

[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)

相关问题 更多 >