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


Example of how to loop over a row 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 row in a numpy array (or 2D matrix) in python ?
How to iterate over a row in a numpy array (or 2D matrix) in python ?

Select a given row

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

To select an entire row, for instance row associated with index 3:

data[3,:]

returns here

array([9, 8, 9, 1, 4, 2, 2, 3])

Iterate over a given row

Now to Iterate over a row:

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

returns

9
8
9
1
4
2
2
3

References

Image

of