【发布时间】:2020-04-27 15:16:44
【问题描述】:
我正在尝试使用 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)
我也遇到过一维数组的问题。我该如何解决?
【问题讨论】:
-
a[yindx]已经给出了一个二维数组,然后您通过在a[yindx,:]中添加逗号和冒号来添加一个维度,以告诉 numpy 为您提供此数组中的所有内容以及第三个中的所有内容维度也是。目前尚不清楚您期望会发生什么不同
标签: python arrays numpy indexing