In python if a define:
a = arange(9).reshape(3,3)
as a 3x3 matrix and iterate:
for i in a:
It'll iterate over the matrix's rows. Is there any way to iterate over columns?
In order to loop over a 2D array, we first go through each row, and then again we go through each column in every row. That's why we need two loops, nested in each other. Anytime, if you want to come out of the nested loop, you can use the break statement.
NumPy package contains an iterator object numpy. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python's standard Iterator interface.
How about
for i in a.transpose():
or, shorter:
for i in a.T:
This may look expensive but is in fact very cheap (it returns a view onto the same data, but with the shape and stride attributes permuted).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With