简体   繁体   English

Python - 如何包装np.ndarray类?

[英]Python - How to wrap the np.ndarray class?

I'm trying to add a functionality to the np.ndarray class. 我正在尝试为np.ndarray类添加一个功能。

I was hoping it would be as simple as the following: 我希望它会像以下一样简单:

class myArray(np.ndarray):

    def __init__(self, *args, **kwargs):
        self = np.array(*args, **kwargs)
        # super(ImArray, self).__init__(*args, **kwargs) <-- my first attempt didn't work
        if self.ndim == 4:
            self.myShape = (self.shape[0]*self.shape[1], self.shape[2]*self.shape[3])
        else:
            self.myShape = self.shape

    def myStuff(self):
        self = self.reshape(self.myShape)

a = np.zeros([2, 2, 2, 2])
myArray(a)
# TypeError: only length-1 arrays can be converted to Python scalars
a = range(10)
myArray(a)
# AttributeError: 'numpy.ndarray' object has no attribute 'myShape'

Please let me know if you want more information or something similar. 如果您想了解更多信息或类似内容,请与我们联系。

EDIT: 编辑:

To give a bit more information abuot why I want to do this, as someone suggested simply making a function might be more appropriate. 为了给出更多信息,为什么我要这样做,因为有人建议简单地创建一个函数可能更合适。

I want to add the following: 我想添加以下内容:

A.newFun(B)

which would be the same as: 这将是相同的:

def newFun(A,B):
    oldShapeA = A.shape
    A = np.matrix( A.reshape([A.shape[0]*A.shape[1], A.shape[2]*A.shape[3]]) )
    oldShapeB = B.shape
    B = np.matrix( B.reshape([1, -1]) )
    out = A*B
    out = np.reshape(out.A, oldShapeA[:2]+oldShapeB)
    return out

I have left out a lot of checks such as that the dimenions are correct etc but hopefully you get the point 我遗漏了很多支票,比如尺寸是正确的等等,但希望你能明白这一点

Subclassing ndarray can be done, but has some subtleties. 子类化ndarray可以完成,但有一些细微之处。 These are explained at length in the NumPy manual . 这些在NumPy手册中详细解释。

I don't really follow what you're trying to do in the subclass, but it's worthing considering the question whether subclassing is the right approach to the problem. 我并没有真正遵循你在子类中尝试做的事情,但是考虑子类化是否是解决问题的正确方法的问题值得考虑。

Sub-classing np.ndarray requires a bit of finesse. np.ndarray进行分类需要一些技巧。 The gory details are here: http://docs.scipy.org/doc/numpy/user/basics.subclassing.html 血淋淋的细节在这里: http//docs.scipy.org/doc/numpy/user/basics.subclassing.html

Specifically, I think this does what you wanted: 具体来说,我认为这可以做你想要的:

class myArray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        this = np.array(*args, **kwargs)
        this = np.asarray(this).view(cls)
        return this

    def __array_finalize__(self, obj):
        if obj.ndim == 4:
            self.myShape = (self.shape[0]*self.shape[1], self.shape[2]*self.shape[3])
        else:
            self.myShape = self.shape

    def myStuff(self):
        self = self.reshape(self.myShape)

To see this in a (more elaborate) real-life use-case, take a look here: https://github.com/arokem/nitime/blob/master/nitime/timeseries.py#L101 要在(更精细的)真实用例中看到这一点,请看一下: https//github.com/arokem/nitime/blob/master/nitime/timeseries.py#L101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM