遍历数组numpy的的第一个D轴 [英] Iterating over first d axes of numpy array
本文介绍了遍历数组numpy的的第一个D轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我给斧头任意数量的数组,我想遍历,说他们的第一个D。我该怎么做呢?
I'm given an array with an arbitrary number of axes, and I want to iterate over, say the first 'd' of them. How do I do this?
起初我以为我会做一个包含所有我想要循环指数通过一个数组,使用
Initially I thought I would make an array containing all the indices I want to loop through, using
i = np.indices(a.shape[:d])
indices = np.transpose(np.asarray([x.flatten() for x in i]))
for idx in indices:
a[idx]
但显然我不能像索引一个数组,即使用包含索引另一个数组。
But apparently I cannot index an array like that, i.e. using another array containing the index.
推荐答案
您可以使用的 ndindex
:
You can use ndindex
:
d = 2
a = np.random.random((2,3,4))
for i in np.ndindex(a.shape[:d]):
print i, a[i]
输出:
(0, 0) [ 0.72730488 0.2349532 0.36569509 0.31244037]
(0, 1) [ 0.41738425 0.95999499 0.63935274 0.9403284 ]
(0, 2) [ 0.90690468 0.03741634 0.33483221 0.61093582]
(1, 0) [ 0.06716122 0.52632369 0.34441657 0.80678942]
(1, 1) [ 0.8612884 0.22792671 0.15628046 0.63269415]
(1, 2) [ 0.17770685 0.47955698 0.69038541 0.04838387]
这篇关于遍历数组numpy的的第一个D轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文