简体   繁体   English

遍历 ndarray 的切片

[英]iterate over slices of an ndarray

Say I have a 3D numpy.array, eg with dimensions xyz, is there a way to iterate over slices along a particular axis?假设我有一个 3D numpy.array,例如尺寸为 xyz,有没有办法沿特定轴迭代切片? Something like:就像是:

for layer in data.slices(dim=2):
    # do something with layer

Edit: To clarify, the example is a dim=3 array, ie shape=(len_x, len_y, len_z).编辑:为了澄清,这个例子是一个dim = 3数组,即shape =(len_x,len_y,len_z)。 Elazar and equivalently kamjagin's solutions work, but aren't that general - you have to construct the [:, :, i] by hand, which means you need to know the dimensions, and the code isn't general enough to handle arrays of arbitrary dimensions. Elazar 和等效 kamjagin 的解决方案有效,但不是那么通用 - 您必须手动构建[:, :, i] ,这意味着您需要知道尺寸,并且代码不够通用,无法处理数组任意维度。 You can fill missing dimension by using something like [..., :] , but again you still have to construct this yourself.您可以使用[..., :]之类的东西来填充缺失的维度,但是您仍然必须自己构建它。

Sorry, should have been clearer, the example was a bit too simple!对不起,应该更清楚,例子有点太简单了!

Iterating over the first dimension is very easy, see below. 迭代第一维很容易,见下文。 To iterate over the others, roll that dimension to the front and do the same: 要迭代其他维度,请将该维度滚动到前面并执行相同操作:

>>> data = np.arange(24).reshape(2, 3, 4)
>>> for dim_0_slice in data: # the first dimension is easy
...     print dim_0_slice
... 
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
>>> for dim_1_slice in np.rollaxis(data, 1): # for the others, roll it to the front
...     print dim_1_slice
... 
[[ 0  1  2  3]
 [12 13 14 15]]
[[ 4  5  6  7]
 [16 17 18 19]]
[[ 8  9 10 11]
 [20 21 22 23]]
>>> for dim_2_slice in np.rollaxis(data, 2):
...     print dim_2_slice
... 
[[ 0  4  8]
 [12 16 20]]
[[ 1  5  9]
 [13 17 21]]
[[ 2  6 10]
 [14 18 22]]
[[ 3  7 11]
 [15 19 23]]

EDIT Some timings, to compare different methods for largish arrays: 编辑一些时间,比较大型阵列的不同方法:

In [7]: a = np.arange(200*100*300).reshape(200, 100, 300)

In [8]: %timeit for j in xrange(100): a[:, j]
10000 loops, best of 3: 60.2 us per loop

In [9]: %timeit for j in xrange(100): a[:, j, :]
10000 loops, best of 3: 82.8 us per loop

In [10]: %timeit for j in np.rollaxis(a, 1): j
10000 loops, best of 3: 28.2 us per loop

In [11]: %timeit for j in np.swapaxes(a, 0, 1): j
10000 loops, best of 3: 26.7 us per loop

This could probably be solved more elegantly than this, but one way of doing it if you know dim beforehand(eg 2) is: 这可能比这更优雅地解决,但如果你事先知道昏暗(例如2),那么这样做的一种方法是:

for i in range(data.shape[dim]):
    layer = data[:,:,i]

or if dim=0 或者如果dim = 0

for i in range(data.shape[dim]):
    layer = data[i,:,:]

etc. 等等

something like that? 这样的事情?

>>> data = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> for layer in [data[:,i] for i in range(3)]:
...     print layer
... 
[1 4 7]
[2 5 8]
[3 6 9]

Correct me if I am wrong but it seems to me that your 3D array is gonna look like : 如果我错了,请纠正我,但在我看来,你的3D阵列看起来像是:

>>> my_array.shape
    (3,N)

Where N is the size of your array. 其中N是数组的大小。 So if you want to iterate over one dimension, you can just do : 因此,如果您想迭代一个维度,您可以这样做:

>>> for item in my_array[1,:]:

This will iterate on the second dimension. 这将迭代第二个维度。

I think the original question was ambiguous, and so is the title:我认为最初的问题是模棱两可的,标题也是如此:

  • Iterating over x[k,:,:,...] for all k yields as many items as x.shape[0] , so I would call this iterating over a dimension ;对所有 k 迭代x[k,:,:,...]会产生与x.shape[0]一样多的项目,因此我将其称为对维度的迭代;
  • In contrast, iterating over a slice in my mind means iterating eg over x[:,i,j,k,...] for all i,j,k.相反,在我的脑海中迭代切片意味着迭代例如在x[:,i,j,k,...]上对所有 i,j,k。 For example, iterating over all columns in an ndarray.例如,遍历 ndarray 中的所有列。

Although that's not what the OP asked after clarification, people looking for a solution to the second case above might find the following code useful:尽管这不是 OP 在澄清后所要求的,但寻找上述第二种情况的解决方案的人可能会发现以下代码很有用:

from itertools import product

def iterslice(x,axis=0):
    sub = [ range(s) for s in x.shape ]
    sub[axis] = (slice(None),)
    for p in product(*sub):
        yield x[p]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM