Ben*_*Ben 5 python oop numpy namedtuple
我真的很喜欢 namedtuple 集合的功能。具体来说,我喜欢它对二维空间中的点有多大用处。
In : from collections import namedtuple
In : Point = namedtuple('Point', ['x', 'y'])
In : p = Point(1,2)
In : p.x
Out: 1
In : p.y
Out: 2
Run Code Online (Sandbox Code Playgroud)
我认为这比引用列表的第一个和第二个条目要清楚得多。我想知道是否有办法使 Point 也是一个 numpy 数组。例如
In: p1 = Point(1,2)
In: p2 = Point(3,4)
In: (p1+p2).x
Out: 4
Run Code Online (Sandbox Code Playgroud)
以及来自 numpy 的类似功能。换句话说,我想我希望 Point 成为 numpy 的子类?我可以这样做吗?如何?
结构化数组point_type不定义涉及多个字段的数学运算。
In [470]: point_type = [('x', float), ('y', float)]
In [471]: points = np.array([(1,2), (3,4), (5,6)], dtype=point_type)
In [472]: points
Out[472]:
array([(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
In [473]: points[0]+points[1]
...
TypeError: unsupported operand type(s) for +: 'numpy.void' and 'numpy.void'
Run Code Online (Sandbox Code Playgroud)
相反,我可以创建一个二维数组,然后将其视为point_type- 数据缓冲区布局将相同:
In [479]: points = np.array([(1,2), (3,4), (5,6)],float)
In [480]: points
Out[480]:
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
In [481]: points.view(point_type)
Out[481]:
array([[(1.0, 2.0)],
[(3.0, 4.0)],
[(5.0, 6.0)]],
dtype=[('x', '<f8'), ('y', '<f8')])
In [482]: points.view(point_type).view(np.recarray).x
Out[482]:
array([[ 1.],
[ 3.],
[ 5.]])
Run Code Online (Sandbox Code Playgroud)
我可以跨行进行数学运算,并继续将结果视为分数:
In [483]: (points[0]+points[1]).view(point_type).view(np.recarray)
Out[483]:
rec.array([(4.0, 6.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
In [484]: _.x
Out[484]: array([ 4.])
In [485]: points.sum(0).view(point_type)
Out[485]:
array([(9.0, 12.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
Run Code Online (Sandbox Code Playgroud)
或者,我可以从 开始point_type,并将其视为数学的 2d,然后查看它
pdt1=np.dtype((float, (2,)))
In [502]: points
Out[502]:
array([(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
In [503]: points.view(pdt1)
Out[503]:
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
In [504]: points.view(pdt1).sum(0).view(point_type)
Out[504]:
array([(9.0, 12.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
Run Code Online (Sandbox Code Playgroud)
因此,可以将数组作为 2d 和 recarray 进行查看和操作。为了漂亮或有用,它可能需要埋在用户定义的类中。
从recarray课堂中汲取想法的另一种选择。从__getattribute__本质上讲,它只是一个具有专门(和 setattribute)方法的结构化数组。该方法首先尝试普通的数组方法和属性(例如x.shape,x.sum)。然后它尝试attr在定义的字段名中进行调整。
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError: # attr must be a fieldname
pass
fielddict = ndarray.__getattribute__(self, 'dtype').fields
try:
res = fielddict[attr][:2]
except (TypeError, KeyError):
raise AttributeError("record array has no attribute %s" % attr)
return self.getfield(*res)
...
Run Code Online (Sandbox Code Playgroud)
points.view(np.recarray).x变成points.getfield(*points.dtype.fields['x']).
另一种方法是借用namedtuple( /usr/lib/python3.4/collections/__init__.py),并定义x和y属性,这将索引二维数组的[:,0]和[:,1]列。将这些属性添加到 的子类中可能是最简单的np.matrix,让该类确保大多数数学结果是二维的。