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?
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.
In numpy, += is implemented to do in memory changes, while + returns a new array.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With