Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy how to iterate over columns of array?

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.

like image 441
User Avatar asked Apr 13 '12 21:04

User


People also ask

How do you iterate columns in a NumPy array?

In each iteration we output a column out of the array using ary[:, col] which means that give all elements of the column number = col. METHOD 2: In this method we would transpose the array to treat each column element as a row element (which in turn is equivalent of column iteration). Code: Python3.

How do you iterate through a column in Python?

One simple way to iterate over columns of pandas DataFrame is by using for loop. You can use column-labels to run the for loop over the pandas DataFrame using the get item syntax ([]) . Yields below output. The values() function is used to extract the object elements as a list.

How do you loop 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.


3 Answers

Just iterate over the transposed of your array:

for column in array.T:
   some_function(column)
like image 200
tillsten Avatar answered Oct 19 '22 21:10

tillsten


This should give you a start

>>> for col in range(arr.shape[1]):
    some_function(arr[:,col])


[1 2 3 4]
[99 14 12 43]
[2 5 7 1]
like image 25
Abhijit Avatar answered Oct 19 '22 20:10

Abhijit


For a three dimensional array you could try:

for c in array.transpose(1, 0, 2):
    do_stuff(c)

See the docs on how array.transpose works. Basically you are specifying which dimension to shift. In this case we are shifting the second dimension (e.g. columns) to the first dimension.

like image 7
stevej Avatar answered Oct 19 '22 19:10

stevej