gpt4 book ai didi

python - 在运行时向 Numpy 数组添加属性

转载 作者:行者123 更新时间:2023-12-04 11:53:57 24 4
gpt4 key购买 nike

我正在尝试使用 setattr 向 Numpy ndarray 添加属性,但出现错误:

import numpy as np

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

AttributeError: numpy.ndarray object has no attribute 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

关于python - 在运行时向 Numpy 数组添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67509913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com