Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over numpy array columnwise

Tags:

python

numpy

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?

like image 442
C_Z_ Avatar asked Jun 23 '26 16:06

C_Z_


1 Answers

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

like image 185
rayryeng Avatar answered Jun 26 '26 05:06

rayryeng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!