在运行时向Numpy数组添加属性
问题描述
我正在尝试使用setattr将属性添加到Numpy ndarray,但收到错误:
import numpy as np
x = np.array([1, 2, 4])
setattr(x, 'new_attr', 1)
AttributeError:numpy.ndarray对象没有属性new_attr
如何向Numpy ndarray添加新属性?
解决方案
使用您的示例并参考Simple example - adding an extra attribute to ndarray,您可以做的事情是
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)
然后
>>> x = np.array([1, 2, 4])
>>> x_ = YourArray(x)
>>> x_.your_new_attr = 2
>>> x_.your_new_attr
2
或直接在实例化时
>>> # x_ = YourArray([1, 2, 4], your_new_attr=3) works as well
>>> x_ = YourArray(x, your_new_attr=3)
>>> x_.your_new_attr
3
相关文章