python – 遍历ndarray的切片
发布时间:2020-12-20 11:28:04 所属栏目:Python 来源:网络整理
导读:假设我有一个3D numpy.array,例如对于尺寸x y z,有没有办法沿特定轴迭代切片?就像是: for layer in data.slices(dim=2): # do something with layer 编辑: 为了澄清,该示例是dim = 3数组,即shape =(len_x,len_y,len_z). Elazar和等效kamjagin的解决方案有
假设我有一个3D numpy.array,例如对于尺寸x y z,有没有办法沿特定轴迭代切片?就像是:
for layer in data.slices(dim=2): # do something with layer 编辑: 对不起,应该更清楚,这个例子有点太简单了! 解决方法
迭代第一维很容易,见下文.要迭代其他维度,请将该维度滚动到前面并执行相同操作:
>>> 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]] 编辑一些时间,比较大型阵列的不同方法: 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,best of 3: 26.7 us per loop (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |