为什么使用数组索引numpy数组会改变形状



我试图使用numpy.where((将二维数组索引到特定值,但除非我在没有:切片的第一个索引中进行索引,否则它总是会增加维度。我在文件中似乎找不到对此的解释。

例如,假设我有一个数组a:

a = np.arange(20)
a = np.reshape(a,(4,5))
print("a = ",a)
print("a shape = ", a.shape)

输出:

a =  [[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]
[15 16 17 18 19]]
a shape =  (4, 5)

如果我有两个索引数组,一个在"x"方向,一个是在"y"方向:

x = np.arange(5)
y = np.arange(4)
xindx = np.where((x>=2)&(x<=4))
yindx = np.where((y>=1)&(y<=2))

然后使用"y"索引对a进行索引,这样就没有问题:

print(a[yindx])
print(a[yindx].shape)

输出:

[[ 5  6  7  8  9]
[10 11 12 13 14]]
(2, 5)

但是,如果我在其中一个索引中有:,那么我就有一个大小为1:的额外维度

print(a[yindx,:])
print(a[yindx,:].shape)
print(a[:,xindx])
print(a[:,xindx].shape)

输出:

[[[ 5  6  7  8  9]
[10 11 12 13 14]]]
(1, 2, 5)
[[[ 2  3  4]]
[[ 7  8  9]]
[[12 13 14]]
[[17 18 19]]]
(4, 1, 3)

我在一维数组中也遇到了这个问题。我该如何解决这个问题?

如果xindxyindx是numpy数组,则结果将如预期。然而,它们是具有单个值的元组。

最简单(也相当愚蠢(的修复:

xindx = np.where((x>=2)&(x<=4))[0]
yindx = np.where((y>=1)&(y<=2))[0]

在只给定条件的情况下,np.where将返回元组中匹配元素的索引。文档中明确不鼓励使用这种方法。

更现实地说,你可能需要这样的东西:

xindx = np.arange(2, 5)
yindx = np.arange(1, 3)

但这实际上取决于我们没有看到的情况

最新更新