Question or problem about Python programming:
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.
How to solve the problem:
Just iterate over the transposed of your array:
for column in array.T: some_function(column)
This should give you a start
>>> for col in range(arr.shape): some_function(arr[:,col]) [1 2 3 4] [99 14 12 43] [2 5 7 1]
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.
for c in np.hsplit(array, array.shape): some_fun(c)
You can also use unzip to iterate through the columns
for col in zip(*array): some_function(col)