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

问题描述 投票:0回答:1

我正在尝试使用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)

我也遇到一维数组的问题。我该如何解决?

python arrays numpy indexing
1个回答
0
投票

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

最简单(也很愚蠢)的解决方法:

xindx = np.where((x>=2)&(x<=4))[0]
yindx = np.where((y>=1)&(y<=2))[0]
© www.soinside.com 2019 - 2024. All rights reserved.