python - numpy ndarray subclass: ufunc don't return scalar type -


for numpy.ndarray subclass, ufunc outputs have same type. in general ufunc scalar output return scalar type (such numpy.float64).

example:

import numpy np  class myarray(np.ndarray):     def __new__(cls, array):         obj = np.asarray(array).view(cls)         return obj  = myarray(np.arange(5)) a*2 # myarray([0, 2, 4, 6, 8])  => same class original (i.e. myarray), ok  a.sum() # myarray(10)               => same original, here i'd expect np.int64  type(2*a) type(a.sum()) # true                     b = a.view(np.ndarray) type(2*b) type(b.sum())     # false 

for standard numpy array, scalar output have scalar type. how have same behavior subclass?

i'm using python 2.7.3 numpy 1.6.2 on osx 10.6

you need override __array_wrap__ in ndarray subclass function looks this:

def __array_wrap__(self, obj):     if obj.shape == ():         return obj[()]    # if ufunc output scalar, return     else:         return np.ndarray.__array_wrap__(self, obj) 

__array_wrap__ called after ufuncs cleanup work. in default implementation special cases exact ndarrays (but not subclasses) convert zero-rank arrays scalars. @ least true versions of numpy.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -