How to iterate over columns of a matrix?

Question:

In python if a define:

a = arange(9).reshape(3,3)

as a 3×3 matrix and iterate:

for i in a:

It’ll iterate over the matrix’s rows. Is there any way to iterate over columns?

Asked By: Rodrigo Souza

||

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

Answered By: NPE

Assuming that a is a well formed matrix, you could try something like:

b = zip(*a)
for index in b:
   ...
Answered By: masterpiga
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.