numpy ndarray subclass: ufunc don't return scalar type

不想你离开。 提交于 2019-12-08 01:22:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!