Let's imagine an empty NumPy array of 3x4 where you've got the coordinate of the top-left corner and the step size in horizontal and vertical direction. Now I would like to know the coordinates for the middle of each cell for the whole array. Like this:
For this I implemented a nested for-loop.
In [12]:
import numpy as np
# extent(topleft_x, stepsize_x, 0, topleft_y, 0, stepsize_y (negative since it's top-left)
extent = (5530000.0, 5000.0, 0.0, 807000.0, 0.0, -5000.0)
array = np.zeros([3,4],object)
cols = array.shape[0]
rows = array.shape[1]
# function to apply to each cell
def f(x,y):
return x*extent[1]+extent[0]+extent[1]/2, y*extent[5]+extent[3]+extent[5]/2
# nested for-loop
def nestloop(cols,rows):
for col in range(cols):
for row in range(rows):
array[col,row] = f(col,row)
In [13]:
%timeit nestloop(cols,rows)
100000 loops, best of 3: 17.4 µs per loop
In [14]:
array.T
Out[14]:
array([[(5532500.0, 804500.0), (5537500.0, 804500.0), (5542500.0, 804500.0)],
[(5532500.0, 799500.0), (5537500.0, 799500.0), (5542500.0, 799500.0)],
[(5532500.0, 794500.0), (5537500.0, 794500.0), (5542500.0, 794500.0)],
[(5532500.0, 789500.0), (5537500.0, 789500.0), (5542500.0, 789500.0)]], dtype=object)
But eager to learn, how can I optimize this? I was thinking of vectorizing or using lambda. I tried to vectorize it as follow:
array[:,:] = np.vectorize(check)(cols,rows)
ValueError: could not broadcast input array from shape (2) into shape (3,4)
But, than I got a broadcasting error. Currently the array is 3 by 4, but this also can become 3000 by 4000.