从numpy数组中提取所有垂直切片 [英] extract all vertical slices from numpy array

查看:152
本文介绍了从numpy数组中提取所有垂直切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ndeumerate或类似方法从3D numpy数组中提取完整的切片.

I want to extract a complete slice from a 3D numpy array using ndeumerate or something similar.

arr = np.random.rand(4, 3, 3)

我想提取所有可能的arr [:, x,y],其中x,y的范围是0到2

I want to extract all possible arr[:, x, y] where x, y range from 0 to 2

推荐答案

ndindex是一种生成与形状相对应的索引的便捷方法:

ndindex is a convenient way of generating the indices corresponding to a shape:

In [33]: arr = np.arange(36).reshape(4,3,3)
In [34]: for xy in np.ndindex((3,3)):
    ...:     print(xy, arr[:,xy[0],xy[1]])
    ...:     
(0, 0) [ 0  9 18 27]
(0, 1) [ 1 10 19 28]
(0, 2) [ 2 11 20 29]
(1, 0) [ 3 12 21 30]
(1, 1) [ 4 13 22 31]
(1, 2) [ 5 14 23 32]
(2, 0) [ 6 15 24 33]
(2, 1) [ 7 16 25 34]
(2, 2) [ 8 17 26 35]

它使用nditer,但是与嵌套的for循环对相比没有任何速度优势.

It uses nditer, but doesn't have any speed advantages over a nested pair of for loops.

In [35]: for x in range(3):
    ...:     for y in range(3):
    ...:         print((x,y), arr[:,x,y])

ndenumerate使用arr.flat作为迭代器,但将其用于

ndenumerate uses arr.flat as the iterator, but using it to

In [38]: for xy, _ in np.ndenumerate(arr[0,:,:]):
    ...:     print(xy, arr[:,xy[0],xy[1]])

做同样的事情,迭代3x3子数组的元素.与ndindex一样,它生成索引.该元素将不是您想要的大小为4的数组,所以我忽略了它.

does the same thing, iterating on the elements of a 3x3 subarray. As with ndindex it generates the indices. The element won't be the size 4 array that you want, so I ignored that.

一种不同的方法是将后面的轴展平,转置,然后在(新的)第一个轴上进行迭代:

A different approach is to flatten the later axes, transpose, and then just iterate on the (new) first axis:

In [43]: list(arr.reshape(4,-1).T)
Out[43]: 
[array([ 0,  9, 18, 27]),
 array([ 1, 10, 19, 28]),
 array([ 2, 11, 20, 29]),
 array([ 3, 12, 21, 30]),
 array([ 4, 13, 22, 31]),
 array([ 5, 14, 23, 32]),
 array([ 6, 15, 24, 33]),
 array([ 7, 16, 25, 34]),
 array([ 8, 17, 26, 35])]

或与以前一样打印:

In [45]: for a in arr.reshape(4,-1).T:print(a)

这篇关于从numpy数组中提取所有垂直切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆