简体   繁体   English

如何迭代Numpy数组的初始尺寸?

[英]How to iterate over initial dimensions of a Numpy array?

I have a Numpy array with shape [1000, 1000, 1000, 3] , being the last dimension, sized 3, is contains the triplets of 3D spatial vectors components. 我有一个形状为[1000, 1000, 1000, 3] 1000,1000,1000,3]的Numpy数组,是最后一个尺寸为3的维,包含3D空间矢量分量的三元组。 How can I use nditer to iterate over each triplet? 如何使用nditer遍历每个三元组? Like this: 像这样:

 for vec in np.nditer(my_array, op_flags=['writeonly', <???>]):
     vec = np.array(something)

I've addressed this question before, but here's a short example: 我之前已经解决了这个问题,但这是一个简短的示例:

vec=np.arange(2*2*2*3).reshape(2,2,2,3)
it=np.ndindex(2,2,2)
for i in it:
    print(vec[i])

producing: 生产:

[0 1 2]
[3 4 5]
[6 7 8]
[ 9 10 11]
[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]

ndindex constructs a multi-index iterator around a dummy array of the size you give it (here (2,2,2) ), and returns it along with a next method. ndindex围绕您提供的大小(此处为(2,2,2) )的虚拟数组构造一个multi-index迭代器,并将其与next方法一起返回。

So you can use ndindex as is, or use it as a model for constructing your on nditer . 因此,您可以ndindex原样使用ndindex ,或将其用作构建on nditer的模型。

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

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