How to change object attributes when overloading __getitem__ in np.ndarray subclassing

26 views Asked by At

I have the following code:

class myarray(np.ndarray):

    def __new__(cls, input_array):
        # Input array is an already formed ndarray instance
        # We first cast to be our class type
        obj = np.asarray(input_array).view(cls)
        obj.col_inds = np.arange(input_array.shape[1])
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.col_inds = getattr(obj, 'col_inds', None)


a = np.random.random((100, 10))
aa = myarray(a)

bb = aa[:, 0:3]
print(bb.col_inds)

The output is [0 1 2 3 4 5 6 7 8 9], what I want should be aa.col_inds[0:3].

I know I should write my own __getitem__(), but I tried many different ways. They all did not work out. What is the proper way to do this?

0

There are 0 answers