Numpy.ndarray:通过数组的特定轴进行迭代

时间:2014-05-28 15:36:30

标签: python numpy

我有一个多维数组。我必须通过一些的轴进行迭代。如果我需要所有轴,我可以使用nditer,但如果我只需要特定的轴,我必须手动完成:

my_array = np.arange(3 * 4 * 5).reshape((3, 4, 5))
for i in range(my_array.shape[0]):
    for j in range(my_array.shape[1]):
        print(i, j)
        # Here should be some processing of the 3rd dimension items of the (i,j)

你不能告诉我一个更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

考虑传递到单个循环,并使用ndindexdocs):

my_array = np.arange(3 * 4 * 5).reshape((3, 4, 5))
for ij in np.ndindex(my_array.shape[:2]):
    i,j=ij
    print(i,j)