2015-06-25 154 views
2

我有一个浮点数的3D numpy数组。我是否索引不正确的数组?我想访问切片124(索引123),但看到这个错误:访问切片的3D numpy阵列

>>> arr.shape 
(31, 285, 286) 
>>> arr[:][123][:] 
Runtime error 
Traceback (most recent call last): 
    File "<string>", line 1, in <module> 
IndexError: index 123 is out of bounds for axis 0 with size 31 

这个错误的原因是什么?

回答

2

arr[:][123][:]是加工品,而不是作为一个整体:你可以试试这个。

arr[:] # just a copy of `arr`; it is still 3d 
arr[123] # select the 123 item along the first dimension 
# oops, 1st dim is only 31, hence the error. 

arr[:, 123, :]被作为整体表达式处理。沿着中间轴选择一个“项目”,并沿着另外两个返回所有内容。

arr[12][123]会工作,因为那首先从第一轴选择一个二维数组。现在,[123]适用于该长度维度,返回1d数组。重复索引[][]..的作品经常足以混淆新编程人员,但通常这不是正确的表达方式。

+0

谢谢!并感谢对arr [:]作为arr的初始副本的澄清。我经常忘记这一点。 –

0

这是你想要的吗?

arr.flatten()[123] 
+0

我敢肯定,这将返回一个单一的值,而不是一个片。 – o11c

1

我想你可能只想做arr[:,123,:]。这给你一个形状为(31,286)的二维数组,其中沿着该轴的第124个位置的内容。

0

查看一些xD数组的切片示例。一块

a[:,123,:]

0
import numpy as np 

s=np.ones((31,285,286)) # 3D array of size 3x3 with "one" values 
s[:,123,:] # access index 123 as you want