你instance
In [470]: instance
Out[470]:
array([('', '', ''), ('', '', ''), ('', '', ''), ('', '', ''),
('', '', ''), ('', '', ''), ('', '', ''), ('', '', ''),
('', '', ''), ('', '', ''), ('', '', ''), ('', '', ''),
('', '', ''), ('', '', ''), ('', '', ''), ('', '', ''),
('', '', ''), ('', '', ''), ('', '', ''), ('', '', '')],
dtype=[('name', '<U100'), ('module', '<U100'), ('offset', '<U30')])
看起來並不像
['One Wire Instance 1', 'One Wire Instance 2', 'One Wire Instance 3']
你說的是一個創紀錄的instance
,這將與每個字符串作爲name
顯示爲
('One Wire Instance 1', 'One Wire Instance 2', 'One Wire Instance 3')
,module
,和offset
。
或者是這3個字符串例如instance['name'][:3]
,3個記錄中的'名稱'字段?
在instance
數組中插入新記錄是一件事,向數組中添加新字段是另一回事。
要與結構數組使用np.insert
,您需要提供正確的D型1個元素的數組。
隨着新instance
:
In [580]: newone = np.array(("module one",'',''),dtype=instance.dtype)
In [581]: newone
Out[581]:
array(('module one', '', ''),
dtype=[('name', '<U100'), ('module', '<U100'), ('offset', '<U30')])
In [582]: np.insert(instance,1,newone)
Out[582]:
array([('Wire 1', '', '0x103'), ('module one', '', ''),
('Wire 2', '', '0x104'), ('Wire 3', '', '0x105')],
dtype=[('name', '<U100'), ('module', '<U100'), ('offset', '<U30')])
np.insert
只是執行這些步驟的功能:
In [588]: instance2 = np.zeros((4,),dtype=instance.dtype)
In [589]: instance2[:1]=instance[:1]
In [590]: instance2[2:]=instance[1:3]
In [591]: instance2
Out[591]:
array([('Wire 1', '', '0x103'), ('', '', ''), ('Wire 2', '', '0x104'),
('Wire 3', '', '0x105')],
dtype=[('name', '<U100'), ('module', '<U100'), ('offset', '<U30')])
In [592]: instance2[1]=newone
In [593]: instance2
Out[593]:
array([('Wire 1', '', '0x103'), ('module one', '', ''),
('Wire 2', '', '0x104'), ('Wire 3', '', '0x105')],
dtype=[('name', '<U100'), ('module', '<U100'), ('offset', '<U30')])
它創建正確的目標大小的新陣,從原始數組複製元素,並將新陣列放入空槽中。
嗨,請檢查編輯,因爲數組索引爲0它將是實例[1] ='','保留' – GoldenEagle