Skip to main content
 首页 » 编程设计

python之子类空 numpy recarray 丢失其类型并在 numpy 1.8 中添加属性

2025年05月04日8bonelee

我正在尝试实现一个 numpy recarray (recsub) 的子类,并将它的实例分配给 dtype 'object' (ndarr) 的 ndarray。它运行良好,但是当用空数组实例化子类 recarray 时我遇到了问题。这是子类重载的代码:

class recsub(numpy.recarray): 
"""subclassed recarray""" 
 
def __new__(cls, *args, **kwargs): 
 
    obj = numpy.recarray.__new__(cls, *args, **kwargs) 
 
    return obj 
 
def __init__(self, *arg, **kwargs): 
 
    self.x = -1 
 
def new_method(self): 
    print 'new_method() : fooooooooooooo' 

我将 ndarray 创建为:

ndarr = numpy.ndarray(5, 'object') 

现在如果我创建两个 recsub 实例:

ndarr[0] = recsub(2, [('a','f8')]) 
ndarr[1] = recsub((), [('a','f8')]) 

现在这里发生了奇怪的事情。的输出:

print type(ndarr[0]) 
print type(ndarr[1]) 

是:

>>> <class '__main__.recsub'> 
>>> <class 'numpy.core.records.record'> 

所以我无法访问 ndarr[1].x

这曾经在 numpy 1.7 中有效,但在 numpy 1.8 中不再有效!因此,在使用形状 () 而不是 (n) 实例化 recarray 时似乎缺少了一些东西

欢迎任何建议,

提前发送,

请您参考如下方法:

我在 dev 1.9 中使用更简单的数组得到了类似的行为

ndarr = np.ndarray(2,dtype=np.object) 
x = np.array([1,2]) 
ndarr[0] = x 
y = np.array(3) 
ndarr[1] = y 
type(ndarr[0]) 
# numpy.ndarray 
type(ndarr[1]) 
# numpy.int32 
ndarr 
# array([array([1, 2]), 3], dtype=object) 

因此形状为 () 的数组作为标量插入到 ndarr 中。

我不知道这是错误、功能还是 1.7 和 1.8 之间某些更改的预期结果。我想首先要看的是 1.8 的发行说明。

这个问题可能相关:https://github.com/numpy/numpy/issues/1679

array([array([]), array(0, object)]) 
array([array([], dtype=float64), 0], dtype=object) 

随着错误修复,https://github.com/numpy/numpy/pull/4109 ,存储为 array 的项目以相同的方式返回(而不是作为标量)。

type(ndarr[1]) 
# <type 'numpy.ndarray'> 
ndarr 
# [array([1, 2]) array(3)] 
# [array([], dtype=float64) array(0, dtype=object)] 
# [array([], dtype=float64) 0] 

并且 OP 示例按预期运行。