简体   繁体   English

子类型化ndarray-如何从普通ndarray进行构造

[英]Subtypingclassing ndarray - how to construct from a normal ndarray

Consider the code below: 考虑下面的代码:

class imarray(np.ndarray):
    def __new__(subtype, shape, dtype=float, buffer=None, offset=0,
          strides=None, order=None):
        if isinstance(shape, np.ndarray):
            obj = shape #doesn't convert subtype.......
        else:
            obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides,
                             order)
        return obj

    def __getitem__(self, key):
        return np.ndarray.__getitem__(self, key)





z = np.zeros([2,3])
x = imarray((2,3))
y = imarray(z)

print(y, type(y))
print(x, type(x))

The line y = imarray(z) should just create a copy and change the type of the array. y = imarray(z)应仅创建一个副本并更改数组的类型。 (but imarray is a subclass of ndarray this should always work anyways). (但是imarray是ndarray的子​​类,无论如何应该总是可以工作)。

How would one do this? 一个人怎么做?

尝试:

obj = shape.view(imarray)

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

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