Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an attribute to a Numpy array in runtime

I am trying to add an attribute to a Numpy ndarray using setattr, but I get an error:

import numpy as np

x = np.array([1, 2, 4])
setattr(x, 'new_attr', 1)

AttributeError: numpy.ndarray object has no attribute new_attr

How can I add a new attribute to a Numpy ndarray?

like image 681
George Avatar asked May 12 '21 19:05

George


People also ask

How do I add a variable to a NumPy array?

You can add a NumPy array element by using the append() method of the NumPy module. The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above.

Can you use += on NumPy array?

In numpy, += is implemented to do in memory changes, while + returns a new array.

Can you add to an array in Python?

If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.


2 Answers

Using your example and refering to Simple example - adding an extra attribute to ndarray, something you can do is

class YourArray(np.ndarray):

    def __new__(cls, input_array, your_new_attr=None):        
        obj = np.asarray(input_array).view(cls)
        obj.your_new_attr = your_new_attr
        return obj

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

and then

>>> x = np.array([1, 2, 4])
>>> x_ = YourArray(x)
>>> x_.your_new_attr = 2
>>> x_.your_new_attr
2

or directly at instantiation

>>> # x_ = YourArray([1, 2, 4], your_new_attr=3) works as well
>>> x_ = YourArray(x, your_new_attr=3)
>>> x_.your_new_attr
3
like image 159
keepAlive Avatar answered Sep 22 '22 13:09

keepAlive


May the metadata type of numpy helps? It allows to set up a new dtype (based on an existing one) where you can attach key value pairs.

For your array, that would be

dt = np.dtype(int, metadata={"new_attr": 1})
x = np.array([1, 2, 4], dtype=dt)
print(x.dtype.metadata)

like image 37
Tobias Windisch Avatar answered Sep 26 '22 13:09

Tobias Windisch