Fix Python – Numpy how to iterate over columns of array?

Question

Asked By – User

Suppose I have and m x n array. I want to pass each column of this array to a function to perform some operation on the entire column. How do I iterate over the columns of the array?

For example, I have a 4 x 3 array like

1  99 2
2  14 5
3  12 7
4  43 1

for column in array:
  some_function(column)

where column would be “1,2,3,4” in the first iteration, “99,14,12,43” in the second, and “2,5,7,1” in the third.

Now we will see solution for issue: Numpy how to iterate over columns of array?


Answer

Just iterate over the transposed of your array:

for column in array.T:
   some_function(column)

This question is answered By – tillsten

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0