Handling attributes of a class within a numpy array
The extra application of modifyvar
to the 1st element results from vectorize
trying to determine the type of array to return. Specifying the otypes
gets around that problem:
vecfunc = np.vectorize(MyClass.modifyvar,otypes=[object])
With this 'inplace' modifier, you don't need to pay attention to what is returned:
vecfunc(myarray2)
is sufficient.
From the vectorize
documentation:
The data type of the output of
vectorized
is determined by calling the function with the first element of the input. This can be avoided by specifying theotypes
argument.
If you defined an add5
method like:
def add5(self): self.myvar1 += 5 return self.myvar1
then
vecfunc = np.vectorize(MyClass.add5,otypes=[int])vecfunc(myarray2)
would return a numeric array, and modify myarray2
at the same time:
array([15, 15, 15, 15, 15, 15, 15, 15, 15, 15])
to display the values I use:
[x.myvar1 for x in myarray2]
I really should define a vectorized 'print'.
This looks like one of the better applications of vectorize
. It doesn't give you any compiled speed, but it does let you use the array notation and broadcasting while operating on your instances one by one. For example vecfunc(myarray2.reshape(2,5))
returns a (2,5)
array of values.