简体   繁体   English

python中的numpy数组字典

[英]Dictionary of numpy array in python

I want to create a data structure of empty numpy array something of this sort: 我想创建一个空的numpy数组的数据结构。

d[1].foo = numpy.arange(x)
d[1].bar = numpy.arange(x)
d[2].foo = numpy.arange(x)
d[2].bar = numpy.arange(x)

What would be the best option ... a list of dictionaries containing numpy arrays? 最好的选择是什么?包含numpy数组的字典列表?

If I define a simple class like: 如果我定义一个简单的类,例如:

class MyObj(object):
    pass
     .

I could create a dictionary with several of these objects: 我可以使用以下几个对象创建字典:

In [819]: d={1:MyObj(), 2:MyObj()}

and then assign attributes to each object 然后为每个对象分配属性

In [820]: d[1].foo=np.arange(3)
In [821]: d[1].bar=np.arange(3)
In [822]: d[2].foo=np.arange(3)
In [823]: d[2].bar=np.arange(3)
In [824]: d
Out[824]: {1: <__main__.MyObj at 0xaf20cfac>, 2: <__main__.MyObj at 0xaf20c4cc>}

Since I didn't define a repr or str the print display isn't very interesting; 由于我没有定义reprstr因此打印显示不是很有趣。

In [825]: vars(d[2])
Out[825]: {'bar': array([0, 1, 2]), 'foo': array([0, 1, 2])}

I could also made a list with these objects 我也可以列出这些对象

In [826]: dl = [None, d[1], d[2]]
In [827]: dl
Out[827]: [None, <__main__.MyObj at 0xaf20cfac>, <__main__.MyObj at 0xaf20c4cc>]
In [828]: vars(dl[1])
Out[828]: {'bar': array([0, 1, 2]), 'foo': array([0, 1, 2])}

So both a list and dictionary can be indexed (so can an array); 这样列表和字典都可以被索引(数组也可以被索引); but the .foo syntax is used to access object attributes. 但是.foo语法用于访问对象属性。

=============== ===============

An entirely different way of creating a structure with this kind of access is to use a recarray - this is a numpy array subclass that allows you to access dtype fields with attribute names 使用这种访​​问创建结构的一种完全不同的方法是使用recarray这是一个numpy数组子类,允许您访问带有属性名称的dtype字段

In [829]: R=np.recarray((3,), dtype=[('foo','O'),('bar','O')])
In [830]: R
Out[830]: 
rec.array([(None, None), (None, None), (None, None)], 
          dtype=[('foo', 'O'), ('bar', 'O')])
In [831]: R[1].foo=np.arange(3)
In [832]: R[2].bar=np.arange(4)
In [833]: R
Out[833]: 
rec.array([(None, None), (array([0, 1, 2]), None), (None, array([0, 1, 2, 3]))], 
          dtype=[('foo', 'O'), ('bar', 'O')])

Here I defined the fields as taking object dtype, which allows me to assign anything, including other arrays to each attribute. 在这里,我将字段定义为采用对象dtype,这使我可以分配任何内容,包括向每个属性分配其他数组。 But usually the dtype is something more specific like int, float, string. 但通常dtype是更具体的东西,例如int,float,string。

I can view the foo attribute/field for all items in the array R : 我可以查看数组R所有项目的foo属性/字段:

In [834]: R.foo
Out[834]: array([None, array([0, 1, 2]), None], dtype=object)
In [835]: R['bar']
Out[835]: array([None, None, array([0, 1, 2, 3])], dtype=object)

A recarray has a special method that allows access to the fields via attribute syntax. recarray具有一种特殊的方法,该方法允许通过attribute语法访问字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM