How can a class that inherits from a NumPy array change its own values?

℡╲_俬逩灬. 提交于 2020-05-27 06:35:10

问题


I have a simple class that inherits from the NumPy n-dimensional array. I want to have two methods of the class that can change the array values of an instance of the class. One of the methods should set the array of the class instance to the values of a list data attribute of the class instance and the other of the methods should append some list values to the array of the class instance. I'm not sure how to accomplish this, but my attempt is as follows:

import numpy

class Variable(numpy.ndarray):

    def __new__(cls, name = "zappo"):
        self = numpy.asarray([]).view(cls)
        self._values            = [1, 2, 3] # list of values
        return(self)

    def updateNumPyArrayWithValues(self):
        self = numpy.asarray(self._values)

    def appendToNumPyArray(self):
        self = numpy.append(self, [4, 5, 6])

a = Variable()
print(a)
a.updateNumPyArrayWithValues()
print(a)

As a quick, preemptive question, would this class survive standard NumPy array operations such as the following?:

>>> v1 = np.array([23, 20, 13, 24, 25, 28, 26, 17, 18, 29])
>>> v1 = v1[v1 >= 20]

So, could I do similar things with my class and have all of its data attributes retained?


回答1:


You can do it like this:

class Variable(np.ndarray):

    def __new__(cls, a):
        obj = np.asarray(a).view(cls)
        return obj

    def updateNumPyArrayWithValues(self):
        self[1] = 1
        return self

>>> v = Variable([1,2,3])
>>> v
Variable([1, 2, 3])
>>> v.updateNumPyArrayWithValues()
Variable([1, 1, 3])
>>> v[v>1]
Variable([3])


来源:https://stackoverflow.com/questions/27910013/how-can-a-class-that-inherits-from-a-numpy-array-change-its-own-values

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