How Does Frompyfunc Iterate Over Arrays?
I am working with large arrays representing a maze routing grid, each element is a Cell object with x,y attributes. I am trying to use numpyfunc to initialize the coordinates in ea
Solution 1:
From your comments and suppose that Cell
objects have x, y
attributes and some other default attribute that doesn't come to play:
classCell:def__init__(self, x,y):
self.x = x
self.y = y
...
Suppose you want a 100*100 array, initiate your array like this:
CellList = [[Cell(x,y) for y in range(100)] for x in range(100)]
# Optional translate it into np.array for easier indexingCellArr = np.array(CellList)
This will return your 100*100 Cell array that has correct Cell elements. To verify:
CellArr[1,2].x
>>>1
Note that numpy
can't actually speed up your array much because Cell
cannot actually go through C code when vectorizing. It could only be used for better indexing.
Vectorizing does not actually help your speed:
%%timeit
CellList = [[Cell(x,y) for y inrange(100)] for x inrange(100)]
# Optional translate it into np.array for easier indexing
CellArr = np.array(CellList)
>>> 24.2 ms ± 542 µs per loop
Vectorizing functions:
def vecX(c, x):c= Cell(x,0)returnc
def vecY(c, y):
c.y = y
returnc
vec = np.vectorize(vecX)
vey = np.vectorize(vecY)
results:
%%timeit
l = []
n = np.zeros((100,100))
for i in range(len(n)):
l.append(vec(n[i, :], i))
CellArr = np.vstack(l)
for j in range(len(CellArr)):
vey(CellArr[:, j], j)
>>> 23.5 ms ± 5 ms per loop
Post a Comment for "How Does Frompyfunc Iterate Over Arrays?"