George
George

Reputation: 93

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?

Upvotes: 6

Views: 3221

Answers (2)

keepAlive
keepAlive

Reputation: 6665

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

Upvotes: 4

Tobias Windisch
Tobias Windisch

Reputation: 1039

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)

Upvotes: 2

Related Questions