Numpy.ndenumerate to return indexes in Fortran order?

When using numpy.ndenumerate indexes are returned as follows for the order of the C-contiguous , for example:

 import numpy as np a = np.array([[11, 12], [21, 22], [31, 32]]) for (i,j),v in np.ndenumerate(a): print i, j, v 

No, if order in a is 'F' or 'C' , this gives:

 0 0 11 0 1 12 1 0 21 1 1 22 2 0 31 2 1 32 

Is there a built-in iterator in numpy like ndenumerate to give this (after the array order='F' ):

 0 0 11 1 0 21 2 0 31 0 1 12 1 1 22 2 1 32 
+4
source share
2 answers

You can do this with np.nditer as follows:

 it = np.nditer(a, flags=['multi_index'], order='F') while not it.finished: print it.multi_index, it[0] it.iternext() 

np.nditer is a very powerful beast that provides part of the internal C-iterator in Python, see Iterating Over Arrays in the docs.

+4
source

Just taking a transpose will give you what you want:

 a = np.array([[11, 12], [21, 22], [31, 32]]) for (i,j),v in np.ndenumerate(aT): print j, i, v 

Result:

 0 0 11 1 0 21 2 0 31 0 1 12 1 1 22 2 1 32 
+3
source

Source: https://habr.com/ru/post/1497575/


All Articles