I want to apply a method to each object in a numpy array. I thought of using numpy.vectorize to speed things up, but I get an empty array instead. I can't figure out what I am doing wrong. Please help!
Here's the code:
import numpy
class Foo(object):
def __init__(self):
self.x = None
def SetX(self, x):
self.x = x
# Initialize and array of Foo objects
y = numpy.empty( 3, dtype=object )
vFoo = numpy.vectorize(lambda x: Foo() )
yfoo = vFoo(y)
# Apply method SetX to each object
xsetter = numpy.vectorize( lambda foo: foo.SetX(3.45) )
print xsetter(yfoo) #[None None None]
Thanks in advance!
The problem is that the lambda function return values is None (the result of Foo.SetX
), you can do this:
def f(foo):
foo.SetX(3.45)
return foo
xsetter = numpy.vectorize( f )
It's because your SetX
method does not return a value. One way to fix this would be by rewriting SetX
as
def SetX(self, x):
self.x = x
return self
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.