[英]Writing to compound dataset with variable length string via h5py (HDF5)
我已經能夠使用h5py在HDF5文件中創建一個由無符號int和長度可變的字符串組成的復合數據集,但是我無法對其進行寫入。
dt = h5py.special_dtype(vlen=str)
dset = fout.create_dataset(ver, (1,), dtype=np.dtype([("time", np.uint64),("value", dt)]))
通過將化合物數據集的特定列設置為等於現有的numpy數組,我已經相當輕松地寫入了其他化合物數據集。
現在,我遇到麻煩的是使用可變長度的字符串寫入復合數據集。 Numpy不支持可變長度的字符串,因此我無法在手工創建包含該值的numpy數組之前。
我的下一個想法是將單個值寫入所討論的列,這對unsigned int有效。 當我嘗試將字符串寫入復合數據集中的可變長度字符串字段時,我得到:
dset["value"] = str("blah")
File "D:\Anaconda3\lib\site-packages\h5py\_hl\dataset.py", line 508, in __setitem__
val = val.astype(numpy.dtype([(names[0], dtype)]))
ValueError: Setting void-array with object members using buffer.
任何指導將不勝感激。
跟隨我之前對v5和h5py一起使用時無法解釋的行為的回答
我運行了此測試( h5py
版本“ 2.2.1”):
In [4]: import h5py
In [5]: dt = h5py.special_dtype(vlen=str)
In [6]: f=h5py.File('foo.hdf5')
In [8]: ds1 = f.create_dataset('JustStrings',(10,), dtype=dt)
In [10]: ds1[0]='string'
In [11]: ds1[1]='a longer string'
In [13]: ds1[2:5]='one_string two_strings three'.split()
In [14]: ds1
Out[14]: <HDF5 dataset "JustStrings": shape (10,), type "|O4">
In [15]: ds1.value
Out[15]:
array(['string', 'a longer string', 'one_string', 'two_strings', 'three',
'', '', '', '', ''], dtype=object)
對於像您這樣的混合dtype:
In [16]: ds2 = f.create_dataset('IntandStrings',(10,),
dtype=np.dtype([("number",int),('astring',dt)]))
In [17]: ds2[0]=(1,'astring')
In [18]: ds2[1]=(10,'a longer string')
In [19]: ds2[2:4]=[(10,'a longer much string'),(0,'')]
In [20]: ds2.value
Out[20]:
array([(1, 'astring'), (10, 'a longer string'),
(10, 'a longer much string'), (0, ''), (0, ''), (0, ''), (0, ''),
(0, ''), (0, ''), (0, '')],
dtype=[('number', '<i4'), ('astring', 'O')])
嘗試自行設置字段似乎無效
ds2['astring'][4]='one two three four'
相反,我必須設置整個記錄:
ds2[4]=(123,'one two three four')
嘗試設置整個字段會產生相同的錯誤:
ds2['astring']='astring'
我將此數據集初始化為(10,)
,而您的數據集為(1,)
。 但是我認為這是同樣的問題。
不過,我可以設置整個數字字段:
In [48]: ds2['number']=np.arange(10)
In [50]: ds2['number']
Out[50]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [51]: ds2.value
Out[51]:
array([(0, 'astring'), (1, 'a longer string'),
(2, 'a longer much string'),
(3, ''), (4, 'one two three four'), (5, ''),
(6, ''), (7, ''),
(8, ''), (9, '')],
dtype=[('number', '<i4'), ('astring', 'O')])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.