The Python Oracle

Numpy how to iterate over columns of array?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping

--

Chapters
00:00 Question
00:40 Accepted answer (Score 290)
00:55 Answer 2 (Score 27)
01:09 Answer 3 (Score 8)
01:37 Answer 4 (Score 6)
01:51 Thank you

--

Full question
https://stackoverflow.com/questions/1014...

Answer 2 links:
[array.transpose]: https://docs.scipy.org/doc/numpy-1.13.0/...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #loops #numpy

#avk47



ACCEPTED ANSWER

Score 300


Just iterate over the transposed of your array:

for column in array.T:
   some_function(column)



ANSWER 2

Score 29


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]



ANSWER 3

Score 8


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.




ANSWER 4

Score 4


for c in np.hsplit(array, array.shape[1]):
    some_fun(c)