How to iterate over columns of a matrix?

2020-02-26 14:56发布

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?

标签: python numpy
2条回答
▲ chillily
2楼-- · 2020-02-26 15:03

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

b = zip(*a)
for index in b:
   ...
查看更多
Deceive 欺骗
3楼-- · 2020-02-26 15:25

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

查看更多
登录 后发表回答