6

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?

4
  • You can't, it's implemented in C. Try to subclass it Commented May 12, 2021 at 19:31
  • Why do you want to add a new attribute to it? Commented May 12, 2021 at 19:31
  • You cannot, the type doesn't allow it. Commented May 13, 2021 at 22:48
  • @LucasNg I require lots of matrix inverses and Matrix_name.I is a particularly handy way , unfortunately the numpy.matrix may be removed from future versions[1] so creating a subclass from np.ndarray with a I (inverse) property is the only option . [1] numpy.org/doc/stable/reference/generated/numpy.matrix.html Commented Oct 30, 2021 at 12:42

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

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)

3 Comments

Doesn't this add the attribute to the type (np.array) and not to an instance (x) ?
@DeepSpace: You are right: Technically, the metadata is attached to the dtype (which, in turn, is attached to the array). I agree, it may be unwiedly to create own dtypes just to attach metadata.
@DeepSpace: No. It attaches the data to the dtype, which is a different thing from the type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.