[Numpy-discussion] Learn about numpy
Folkert Boonstra
F.Boonstra at inter.nl.net
Sun May 4 05:52:44 EDT 2008
With a python background but new to numpy, I have the following.
Suppose I have a 2-D array and I want to apply a function to each element.
The function needs to access the direct neighbouring elements in order
to set a new value for the element. How would I do that in the most
efficient way with numpy?
Currently I have a uint8 array (self.bufbw) filled with 0 and 1 elements:
def applyRule(self, rule):
for xy in self.xydims:
rule(xy)
def rule(self, xy):
x = xy[0]; y = xy[1]
sum = self.bufbw[x-1:x+2, y-1:y+2].sum() \
- self.bufbw[x-1,y-1] - self.bufbw[x+1,y-1] \
- self.bufbw[x-1,y+1] - self.bufbw[x+1,y+1]
if sum == 1:
self.bufbw[x,y] = 1
else:
self.bufbw[x,y] = 0
I have looked at the documentation online but couldn't find another faster solution yet.
Does anyone want to share some ideas on a faster solution with numpy?
Thanks,
Folkert
More information about the NumPy-Discussion
mailing list