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]