[英]How can I implement a dictionary whose value is mutable length array in numpy
我想使用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]
},
您顯示的是一本字典,其值也是字典。 嵌套字典的某些值是標量,其他值是列表。 neighbors
列表的長度有所不同。
我可以圖片創建一個結構化的數組,其中包含與內部字典鍵相對應的字段。
coordinates
和v-state
字段的內部尺寸甚至可以為(2,)和(4,)。
但是對於可變長度的neighbors
或hosts
,我們可以做到最好,將那些字段定義為具有對象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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.