How to iterate over a column in a numpy array (or 2D matrix) in python ?


Example of how to loop over a column in a numpy array (or 2D matrix) in python :

Create an a numpy array

Let's first create a random numpy array:

import numpy as np

data = np.random.randint(10, size=(10,8))

print(data)

returns for example

[[9 6 7 8 6 4 4 9]
 [1 1 4 0 4 6 0 1]
 [6 9 2 2 8 6 8 0]
 [9 8 9 1 4 2 2 3]
 [3 3 4 8 9 9 5 4]
 [5 4 2 8 7 3 4 7]
 [0 1 0 0 0 3 0 2]
 [7 2 6 5 4 4 5 2]
 [5 2 6 5 6 2 2 2]
 [3 1 0 5 9 2 2 2]]

Array visualization with seaborn

Note: If you want to quickly visualize a not too large numpy array, a solution is to use seaborn with heatmap, example

import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

ax = sns.heatmap(data, annot=True, fmt="d")

plt.savefig("iterate_over_a_numpy_array_column.png", bbox_inches='tight', dpi=100)

plt.show()

returns

How to iterate over a column in a numpy array (or 2D matrix) in python ?
How to iterate over a column in a numpy array (or 2D matrix) in python ?

Select a given column

Note: in python column indices start at 0 (Zero-based numbering).

To select an entire column, for instance column associated with index 4:

data[:,4]

returns here

array([6, 4, 8, 4, 9, 7, 0, 4, 6, 9])

Iterate over a given column

Now to Iterate over a column:

for e in data[:,4]:
    print(e)

returns

6
4
8
4
9
7
0
4
6
9

References

Image

of