Home > Back-end >  setting Numpy array elements with a class object
setting Numpy array elements with a class object

Time:05-29

I have created a class called Tensor

import numpy as np

class Tensor:
    def __init__(self, data):
        self.data = np.array(data)

and I'd like to set elements of a numpy array using Tensor:

x = np.array([[1,2,3,4],[4,3,2,1]])
x[:,::2] = Tensor([[0,0],[1,1]])

but it results an error ValueError: setting an array element with a sequence.

one workaround is to retrieve Tensor's data attribute: x[:,::2] = Tensor([[0,0],[1,1]]).data, but I'd like to know how to do it without manually retrieving anything, like when you can set values with a list or numpy array: x[:,::2] = [[0,0],[1,1]] or x[:,::2] = np.array([[0,0],[1,1]])

Thanks for the help!

CodePudding user response:

Numpy array objects all follow a protocol, as long as you implement __array__ method, you can use the object as an array:

>>> class Tensor:
...     def __init__(self, data):
...         self.data = np.array(data)
...     def __array__(self, dtype=None):
...         return self.data    # self.data.astype(dtype, copy=False) maybe better
...
>>> x[:,::2] = Tensor([[0,0],[1,1]])
>>> x
array([[0, 2, 0, 4],
       [1, 3, 1, 1]])

Reference: Writing custom array containers

  • Related