使用不同大小的h5py阵列进行存储

2024-05-15 01:04:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用HDF5数据格式存储大约3000个numpy阵列。数组的长度从5306到121999 np.float64不等

我得到了 Object dtype dtype('O') has no native HDF5 equivalent 错误,因为由于数据的不规则性,numpy使用通用对象类。

我的想法是将所有数组的长度填充到121999,并将大小存储到另一个数据集中。

然而,这在空间上似乎相当低效,有没有更好的方法?

编辑:为了澄清,我想存储3126个dtype = np.float64数组。我把它们存储在一个list中,当h5py执行这个例程时,它会转换成一个dtype = object数组,因为它们的长度不同。为了说明这一点:

a = np.array([0.1,0.2,0.3],dtype=np.float64)
b = np.array([0.1,0.2,0.3,0.4,0.5],dtype=np.float64)
c = np.array([0.1,0.2],dtype=np.float64)

arrs = np.array([a,b,c]) # This is performed inside the h5py call
print(arrs.dtype)
>>> object
print(arrs[0].dtype)
>>> float64

Tags: 数据numpyobjectnp数组arrayhdf5has
2条回答

可变长度内部数组的清除方法: http://docs.h5py.org/en/latest/special.html?highlight=dtype#arbitrary-vlen-data

hdf5_file = h5py.File('yourdataset.hdf5', mode='w')
dt = h5py.special_dtype(vlen=np.dtype('float64'))
hdf5_file.create_dataset('dataset', (3,), dtype=dt)
hdf5_file['dataset'][...] = arrs

print (hdf5_file['dataset'][...])
>>>array([array([0.1,0.2,0.3],dtype=np.float64), 
>>>array([0.1,0.2,0.3,0.4,0.5],dtype=np.float64, 
>>>array([0.1,0.2],dtype=np.float64], dtype=object)

仅适用于1D数组,https://github.com/h5py/h5py/issues/876

看起来你试过像是:

In [364]: f=h5py.File('test.hdf5','w')    
In [365]: grp=f.create_group('alist')

In [366]: grp.create_dataset('alist',data=[a,b,c])
...
TypeError: Object dtype dtype('O') has no native HDF5 equivalent

但是,如果将数组另存为单独的数据集,则它可以工作:

In [367]: adict=dict(a=a,b=b,c=c)

In [368]: for k,v in adict.items():
    grp.create_dataset(k,data=v)
   .....:     

In [369]: grp
Out[369]: <HDF5 group "/alist" (3 members)>

In [370]: grp['a'][:]
Out[370]: array([ 0.1,  0.2,  0.3])

以及访问组中的所有数据集:

In [389]: [i[:] for i in grp.values()]
Out[389]: 
[array([ 0.1,  0.2,  0.3]),
 array([ 0.1,  0.2,  0.3,  0.4,  0.5]),
 array([ 0.1,  0.2])]

相关问题 更多 >

    热门问题