Python – Iterate over numpy array columnwise

numpypython

np.nditer automatically iterates of the elements of an array row-wise. Is there a way to iterate of elements of an array columnwise?

x = np.array([[1,3],[2,4]])

for i in np.nditer(x):
    print i

# 1
# 3
# 2
# 4

What I want is:

for i in Columnwise Iteration(x):
    print i
# 1
# 2
# 3
# 4

Is my best bet just to transpose my array before doing the iteration?

Best Answer

For completeness, you don't necessarily have to transpose the matrix before iterating through the elements. With np.nditer you can specify the order of how to iterate through the matrix. The default is usually row-major or C-like order. You can override this behaviour and choose column-major, or FORTRAN-like order which is what you desire. Simply specify an additional argument order and set this flag to 'F' when using np.nditer:

In [16]: x = np.array([[1,3],[2,4]])

In [17]: for i in np.nditer(x,order='F'):
   ....:     print i
   ....:     
1
2
3
4

You can read more about how to control the order of iteration here: http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.nditer.html#controlling-iteration-order