+1 vote
in Programming Languages by (89.5k points)
I want to read all the rows of each column in a Numpy array. Is there any Python Numpy function for it or is there any Pythonic way to do it?

1 Answer

+3 votes
by (66.6k points)
selected by
 
Best answer

To iterate over columns in a NumPy array, you can use one of the following approaches:

Approach 1: You can iterate over columns using slicing.

import numpy as np

# Sample NumPy array

num_arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [10, 20, 30, 40]])

# iterate over columns

for i in range(num_arr.shape[1]):

    print(num_arr[:, i])

Approach 2: You can transpose the array and iterate over rows (which are originally columns).

# Transpose the array

for col in num_arr.T:

    print(col)

Both of these approaches will produce the following result:

 [ 1  5 10]

[ 2  6 20]

[ 3  7 30]

[ 4  8 40]


...