问题
For numpy.ndarray
subclass, ufunc outputs have the same type. This is good in general but I would like for ufunc with scalar output to return scalar type (such as numpy.float64
).
Example:
import numpy as np
class MyArray(np.ndarray):
def __new__(cls, array):
obj = np.asarray(array).view(cls)
return obj
a = MyArray(np.arange(5))
a*2
# MyArray([0, 2, 4, 6, 8]) => same class as original (i.e. MyArray), ok
a.sum()
# MyArray(10) => same as original, but here I'd expect np.int64
type(2*a) is type(a.sum())
# True
b = a.view(np.ndarray)
type(2*b) is type(b.sum())
# False
For standard numpy array, scalar output have scalar type. So how to have the same behavior for my subclass?
I'm using Python 2.7.3 with numpy 1.6.2 on an OSX 10.6
回答1:
You need to override __array_wrap__
in your ndarray subclass with a function that looks like this:
def __array_wrap__(self, obj):
if obj.shape == ():
return obj[()] # if ufunc output is scalar, return it
else:
return np.ndarray.__array_wrap__(self, obj)
__array_wrap__
is called after ufuncs to do cleanup work. In the default implementation special cases exact ndarrays (but not subclasses) to convert zero-rank arrays to scalars. At least this is true for some versions of numpy.
来源:https://stackoverflow.com/questions/19223926/numpy-ndarray-subclass-ufunc-dont-return-scalar-type