记录/记录数组在
中实现
https://github.com/numpy/numpy/blob/master/numpy/core/records.py
此文件中的一些相关引述
记录数组
记录数组将结构化数组的字段公开为属性。
recarray 几乎与标准数组相同(它支持
已命名字段)最大的区别是它可以使用
属性查找来查找字段,它是使用构造的
记录。
recarray 是ndarray 的子类(与matrix 和masked arrays 相同)。但请注意,它的构造函数与np.array 不同。它更像np.empty(size, dtype)。
class recarray(ndarray):
"""Construct an ndarray that allows field access using attributes.
This constructor can be compared to ``empty``: it creates a new record
array but does not fill it with data.
实现唯一字段作为属性行为的关键函数是__getattribute__(__getitem__实现索引):
def __getattribute__(self, attr):
# See if ndarray has this attr, and return it if so. (note that this
# means a field with the same name as an ndarray attr cannot be
# accessed by attribute).
try:
return object.__getattribute__(self, attr)
except AttributeError: # attr must be a fieldname
pass
# look for a field with this name
fielddict = ndarray.__getattribute__(self, 'dtype').fields
try:
res = fielddict[attr][:2]
except (TypeError, KeyError):
raise AttributeError("recarray has no attribute %s" % attr)
obj = self.getfield(*res)
# At this point obj will always be a recarray, since (see
# PyArray_GetField) the type of obj is inherited. Next, if obj.dtype is
# non-structured, convert it to an ndarray. If obj is structured leave
# it as a recarray, but make sure to convert to the same dtype.type (eg
# to preserve numpy.record type if present), since nested structured
# fields do not inherit type.
if obj.dtype.fields:
return obj.view(dtype=(self.dtype.type, obj.dtype.fields))
else:
return obj.view(ndarray)
它首先尝试获取一个常规属性——例如.shape、.strides、.data,以及所有方法(.sum、.reshape 等)。如果失败,它会在 dtype 字段名称中查找名称。所以它实际上只是一个结构化数组,带有一些重新定义的访问方法。
据我所知,record array 和 recarray 是相同的。
另一个文件显示了一些历史记录
https://github.com/numpy/numpy/blob/master/numpy/lib/recfunctions.py
用于操作结构化数组的实用程序集合。
其中大部分功能最初是由 John Hunter 实现的
matplotlib。为方便起见,它们已被重写和扩展。
此文件中的许多函数都以:
if asrecarray:
output = output.view(recarray)
您可以将数组返回为recarray 视图这一事实表明该层有多“薄”。
numpy 历史悠久,合并了几个独立的项目。我的印象是recarray 是一个较老的想法,而结构化数组是当前基于广义dtype 的实现。与任何新开发相比,recarrays 似乎是为了方便和向后兼容而保留的。但我必须研究github 文件历史记录,以及任何最近的问题/拉取请求以确定。