numpy ndarray子类:ufunc不返回标量类型 [英] numpy ndarray subclass: ufunc don't return scalar type

查看:104
本文介绍了numpy ndarray子类:ufunc不返回标量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于numpy.ndarray子类,ufunc输出具有相同的类型.一般来说,这很好,但我希望带标量输出的ufunc返回标量类型(例如numpy.float64).

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).

示例:

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

对于标准numpy数组,标量输出具有标量类型.那么,如何使我的子类具有相同的行为?

For standard numpy array, scalar output have scalar type. So how to have the same behavior for my subclass?

我在OSX 10.6上将Python 2.7.3与numpy 1.6.2一起使用

I'm using Python 2.7.3 with numpy 1.6.2 on an OSX 10.6

推荐答案

您需要使用以下函数重写ndarray子类中的__array_wrap__:

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)

在ufunc之后调用

__array_wrap__进行清理工作.在默认实现中,特殊情况下使用精确的ndarrays(但不包括子类)将零级数组转换为标量.至少对于某些版本的numpy如此.

__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.

这篇关于numpy ndarray子类:ufunc不返回标量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆