[英]Iterating over first d axes of numpy array
I'm given an array with an arbitrary number of axes, and I want to iterate over, say the first 'd' of them. 我给了一个具有任意数量轴的数组,我想迭代,说出它们的第一个'd'。 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, ie using another array containing the index. 但显然我不能像这样索引数组,即使用另一个包含索引的数组。
You can use ndindex
: 你可以使用ndindex
:
d = 2
a = np.random.random((2,3,4))
for i in np.ndindex(a.shape[:d]):
print i, a[i]
Output: 输出:
(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]
You could reshape a
to compress the 1st d
dimensions into one: 您可以重塑a
以将第一个d
维度压缩为一个:
for x in a.reshape(-1,*a.shape[d:]):
print x
or 要么
aa=a.reshape(-1,*a.shape[d:])
for i in range(aa.shape[0]):
print aa[i]
We really need to know more about what you need to do with a[i]
. 我们真的需要了解更多关于你需要做什么a[i]
。
shx2
uses np.ndenumerate
. shx2
使用np.ndenumerate
。 The doc for that function mentions ndindex
. 该函数的doc提到了ndindex
。 That could be used as: 这可以用作:
for i in np.ndindex(a.shape[:d]):
print i
print a[i]
Where i
is a tuple. i
是一个元组。 It's instructive to look at the Python code for these functions. 查看这些函数的Python代码是有益的。 ndindex
for example uses nditer
. ndindex
例如使用nditer
。
Write a simple recursive function: 写一个简单的递归函数:
import numpy as np
data = np.random.randint(0,10,size=4).reshape((1,1,1,1,2,2))
def recursiveIter(d, level=0):
print level
if level <= 2:
for item in d:
recursiveIter(item, level+1)
else:
print d
recursiveIter(data)
outputs: 输出:
0
1
2
3
[[[2 5]
[6 0]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.