Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through 2D numpy array using x and y coordinates without getting out of bounds error?

I have tried the following:

import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) print a rows = a.shape[0] cols = a.shape[1] print rows print cols  for x in range(0, cols - 1):     for y in range(0, rows -1):         print a[x,y] 

This will only print numbers 1 - 6.

I have also tried only subtracting 1 from either rows or cols in the range, but that either leads to out of bounds error or not all numbers printed.

like image 650
CompSci-PVT Avatar asked May 28 '15 07:05

CompSci-PVT


People also ask

Can you loop through a NumPy array?

Numpy for loop is used for iterating through numpy arrays of different dimensions, which is created using the python numpy library and using the for loop, multiple operations can be done going through each element in the array by one.

How do you slice a 2D NumPy array in Python?

To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .


2 Answers

You get prettier code with:

for iy, ix in np.ndindex(a.shape):     print(a[iy, ix]) 

resulting in:

1 2 3 4 5 6 7 8 9 10 11 12 
like image 106
Markus Dutschke Avatar answered Oct 11 '22 04:10

Markus Dutschke


a.shape[0] is the number of rows and the size of the first dimension, while a.shape[1] is the size of the second dimension. You need to write:

for x in range(0, rows):     for y in range(0, cols):         print a[x,y] 

Note how rows and cols have been swapped in the range() function.

Edit: It has to be that way because an array can be rectangular (i.e. rows != cols). a.shape is the size of each dimension in the order they are indexed. Therefore if shape is (10, 5) when you write:

a[x, y] 

the maximum of x is 9 and the maximum for y is 4. x and y are actually poor names for array indices, because they do not represent a mathematical cartesisan coordinate system, but a location in memory. You can use i and j instead:

for i in range(0, rows):     for j in range(0, cols):         print a[i,j] 

The documentation is a bit long but has a good in-depth description of indices and shapes.

like image 44
fouronnes Avatar answered Oct 11 '22 03:10

fouronnes