Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over columns of a matrix?

Tags:

python

numpy

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?

like image 244
Rodrigo Souza Avatar asked Apr 01 '11 15:04

Rodrigo Souza


People also ask

How do you iterate over a column in a 2D array?

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.

Can you iterate over a Numpy array?

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.


1 Answers

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).

like image 193
NPE Avatar answered Oct 03 '22 23:10

NPE