簡體   English   中英

Python和Numpy:使用multi_index遍歷特定軸嗎?

[英]Python & Numpy: Iterating over specific axes with multi_index?

我有五個軸的數組:

colors = numpy.zeros(3, 3, 3, 6, 3))

我想像從此鏈接的第二個示例一樣使用multi_index對其進行迭代,但是我不想遍歷整個5個維度,而是要遍歷前三個維度。 使用Python的方式(不涉及Numpy)將如下所示:

indexes = itertools.product(range(3), repeat=3)
for coordinates in indexes:
  colors[coordinates]

如何在純Numpy中實現呢?

我們numpy.ndindex()

for idx in np.ndindex(*colors.shape[:3]):
    data = colors[coordinates]

據我了解的問題,您主要想要的是numpy替代itertools.product()。 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM