【问题标题】:Why does indexing a numpy array using an array change the shape?为什么使用数组索引 numpy 数组会改变形状?
【发布时间】: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


【解决方案1】:

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

最简单(而且相当愚蠢)的修复:

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

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

更现实地说,您可能需要类似的东西:

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

...但这真的取决于我们看不到的上下文

【讨论】:

    猜你喜欢
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2023-03-09
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多