Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.ndenumerate to return indices in Fortran order?

When using numpy.ndenumerate the indices are returned following for a C-contiguous array order, 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 mather if the 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 any built-in iterator in numpy like ndenumerate to give this (following the array order='F'):

0 0 11
1 0 21
2 0 31
0 1 12
1 1 22
2 1 32
like image 355
Saullo G. P. Castro Avatar asked Mar 23 '23 17:03

Saullo G. P. Castro


1 Answers

You can do it 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 exposes some of the internal C iterator in Python, take a look at Iterating Over Arrays in the docs.

like image 93
Jaime Avatar answered Apr 06 '23 19:04

Jaime