我有一个有五个轴的数组:
colors = numpy.zeros(3, 3, 3, 6, 3))我想像this link中的第二个示例那样使用multi_index迭代它,但是我不想迭代整个5维,而是迭代前3维。一种Pythonic式的方法(不涉及Numpy)是这样的:
indexes = itertools.product(range(3), repeat=3)
for coordinates in indexes:
colors[coordinates]我如何在纯Numpy中实现这一点?
发布于 2013-12-29 11:54:39
美国numpy.ndindex()
for idx in np.ndindex(*colors.shape[:3]):
data = colors[coordinates]发布于 2013-12-29 11:55:49
据我所知,您主要想要的是itertools.product()的numpy替代品。numpy中最接近的类比应该是numpy.indices()。如果我们稍微修改一下问题中的代码样本,以便向我们展示它的输出是什么,当我们在numpy中工作时,我们需要能够重现:
indexes = itertools.product(range(3), repeat=3)
for coordinates in indexes:
print(coordinates)我们得到以下结果:
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(2, 0, 0)
(2, 0, 1)
(2, 0, 2)
(2, 1, 0)
(2, 1, 1)
(2, 1, 2)
(2, 2, 0)
(2, 2, 1)
(2, 2, 2)下面的代码示例将使用numpy.indices()而不是itertools.product()逐行准确地重现此结果:
import numpy
a, b, c = numpy.indices((3,3,3))
indexes = numpy.transpose(numpy.asarray([a.flatten(), b.flatten(), c.flatten()]))
for coordinates in indexes:
print(tuple(coordinates))https://stackoverflow.com/questions/20821050
复制相似问题