【问题标题】:How can I implement a dictionary whose value is mutable length array in numpy如何在numpy中实现其值为可变长度数组的字典
【发布时间】:2017-04-25 16:34:09
【问题描述】:

我想用numpy来实现下面的数据结构。现在我用python字典来做这个工作,但是向量操作很难做,我要多次添加向量,所以我想用numpy来简化工作。主机的长度在程序执行期间会有所不同。我是否可以使用 numpy 结构化数组来完成这项工作,请注意列表的长度是可变的?我不熟悉,只是想知道有没有可能,以免浪费时间。

{
  "0" :{
      "coordinates": [100, 100],
      "neighbours": [1, 40],
      "hosts":[],
      "v-capacity":20,
      "v-immature":0,
      "v-state":[20, 0, 0, 0]
  },
  "1" :{
      "coordinates": [200, 100],
      "neighbours": [0, 2, 41],
      "hosts":[],
      "v-capacity":20,
      "v-immature":0,
      "v-state":[20, 0, 0, 0]
  },

【问题讨论】:

  • 您能否举例说明您需要对这些数据执行哪些操作?例如。跨多个 coordinatesv-states 的聚合?
  • @wilkesybear 是的,基本上,这个数据结构被用于疾病模拟器。宿主在程序执行过程中会追加新元素,v-state是一个向量,经常会做向量的加减,例如a["1"]["v-state"] += a["2"][ “v-状态”]。问题是我必须通过使用函数调用或在 python 中耗时的循环来执行这些向量操作。所以我想用 numpy 代替。

标签: python numpy dictionary


【解决方案1】:

你展示的是一个字典,它的值也是字典。嵌套字典的一些值是标量,另一些是列表。 neighbors 列表长度不同。

我可以想象创建一个结构化数组,其中的字段对应于内部字典键。

coordinatesv-state 字段甚至可以具有 (2,) 和 (4,) 的内部维度。

但对于可变长度neighborshosts,我们最好将这些字段定义为具有对象 dtype,这会将相应的列表存储在内存中的其他位置。这种数组的数学运算是有限的。

但在深入了解结构化数组之前,请先探索创建一组数组来存储这些数据,out 字典中的每个项目都有一个 row

coordinates = np.array([[100,100],[200,100]])
neighbors = np.array([[1, 40],[0, 2, 41]])

确保您了解这些表达式的含义。

In [537]: coordinates
Out[537]: 
array([[100, 100],
       [200, 100]])
In [538]: neighbors
Out[538]: array([[1, 40], [0, 2, 41]], dtype=object)

这是一个可以容纳这些数组的结构化数组示例:

In [539]: dt=np.dtype([('coordinates',int,(2,)),('neighbors',object)])
In [540]: arr = np.zeros((2,), dtype=dt)
In [541]: arr
Out[541]: 
array([([0, 0], 0), ([0, 0], 0)], 
      dtype=[('coordinates', '<i4', (2,)), ('neighbors', 'O')])
In [543]: arr['coordinates']=coordinates
In [544]: arr['neighbors']=neighbors
In [545]: arr
Out[545]: 
array([([100, 100], [1, 40]), ([200, 100], [0, 2, 41])], 
      dtype=[('coordinates', '<i4', (2,)), ('neighbors', 'O')])
In [546]: arr['neighbors']
Out[546]: array([[1, 40], [0, 2, 41]], dtype=object)

注意,这基本上是一种包装方便。它将数组存储在一个地方,但您仍然需要对各个字段执行数学/向量运算。

In [547]: coordinates.sum(axis=1)
Out[547]: array([200, 300])     # sum across columns of a 2d array
In [548]: neighbors.sum()
Out[548]: [1, 40, 0, 2, 41]    # sum (concatenate) of lists

【讨论】:

  • 非常感谢,保罗。你的回答给了我很多启发,我会试试的
猜你喜欢
  • 2016-12-19
  • 1970-01-01
  • 2011-01-15
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2016-06-19
  • 1970-01-01
相关资源
最近更新 更多