[英]Iterate across arbitrary dimension in numpy
I have a multidimensional numpy array, and I need to iterate across a given dimension. 我有一个多维的numpy数组,我需要迭代给定的维度。 Problem is, I won't know which dimension until runtime.
问题是,直到运行时我才知道哪个维度。 In other words, given an array m, I could want
换句话说,给定一个数组m,我可能想要
m[:,:,:,i] for i in xrange(n)
or I could want 或者我想要的
m[:,:,i,:] for i in xrange(n)
etc. 等等
I imagine that there must be a straightforward feature in numpy to write this, but I can't figure out what it is/what it might be called. 我想在numpy中必须有一个简单的功能来写这个,但我无法弄清楚它是什么/它可能被称为什么。 Any thoughts?
有什么想法吗?
There are many ways to do this. 有很多方法可以做到这一点。 You could build the right index with a list of slices, or perhaps alter
m
's strides. 您可以使用切片列表构建正确的索引,或者可能改变
m
的步幅。 However, the simplest way may be to use np.swapaxes
: 但是,最简单的方法可能是使用
np.swapaxes
:
import numpy as np
m=np.arange(24).reshape(2,3,4)
print(m.shape)
# (2, 3, 4)
Let axis
be the axis you wish to loop over. 让
axis
成为您想要循环的轴。 m_swapped
is the same as m
except the axis=1
axis is swapped with the last ( axis=-1
) axis. 除了
axis=1
轴与最后一个( axis=-1
)轴交换外, m_swapped
与m
相同。
axis=1
m_swapped=m.swapaxes(axis,-1)
print(m_swapped.shape)
# (2, 4, 3)
Now you can just loop over the last axis: 现在你可以遍历最后一个轴:
for i in xrange(m_swapped.shape[-1]):
assert np.all(m[:,i,:] == m_swapped[...,i])
Note that m_swapped
is a view, not a copy, of m
. 请注意,
m_swapped
是m
的视图,而不是副本。 Altering m_swapped
will alter m
. 改变
m_swapped
将改变m
。
m_swapped[1,2,0]=100
print(m)
assert(m[1,0,2]==100)
You can use slice(None)
in place of the :
. 您可以使用
slice(None)
代替:
。 For example, 例如,
from numpy import *
d = 2 # the dimension to iterate
x = arange(5*5*5).reshape((5,5,5))
s = slice(None) # :
for i in range(5):
slicer = [s]*3 # [:, :, :]
slicer[d] = i # [:, :, i]
print x[slicer] # x[:, :, i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.