Numpy 用h5py中相同值的复合数据填充数据集的快速方法

Numpy 用h5py中相同值的复合数据填充数据集的快速方法,numpy,hdf5,h5py,Numpy,Hdf5,H5py,我有一个hdf文件中的大型复合数据集。复合数据的类型如下所示: numpy.dtype([('Image', h5py.special_dtype(ref=h5py.Reference)), ('NextLevel', h5py.special_dtype(ref=h5py.Reference))]) 使用它,我创建了一个数据集,其中引用了一个图像,并在每个位置创建了另一个数据集。 这些数据集的维数为nxn,通常n至少为256,但更可能大于2000。

我有一个hdf文件中的大型复合数据集。复合数据的类型如下所示:

    numpy.dtype([('Image', h5py.special_dtype(ref=h5py.Reference)), 
                 ('NextLevel', h5py.special_dtype(ref=h5py.Reference))])
使用它,我创建了一个数据集,其中引用了一个图像,并在每个位置创建了另一个数据集。 这些数据集的维数为nxn,通常n至少为256,但更可能大于2000。 我必须首先用相同的值填充这些数据集的每个位置:

    [[(image.ref, dataset.ref)...(image.ref, dataset.ref)],
      .
      .
      .
     [(image.ref, dataset.ref)...(image.ref, dataset.ref)]]
我尽量避免使用两个for循环来填充它,例如:

    for i in xrange(0,n):
      for j in xrange(0,n):
         daset[i,j] =(image.ref, dataset.ref)
因为性能很差。 因此,我正在搜索类似于
numpy.fill
numpy.shape
numpy.reformate
numpy.array
numpy.arrangement
[:]
等内容。我以各种方式尝试了这些函数,但它们似乎都只适用于数字和字符串数据类型。 有没有办法比for循环更快地填充这些数据集

提前谢谢。

您可以使用numpy或
numpy的组合。重复
numpy。重塑

my_dtype = numpy.dtype([('Image', h5py.special_dtype(ref=h5py.Reference)), 
             ('NextLevel', h5py.special_dtype(ref=h5py.Reference))])
ref_array = array( (image.ref, dataset.ref), dtype=my_dtype)
dataset = numpy.repeat(ref_array, n*n)
dataset = dataset.reshape( (n,n) )
请注意,
numpy.repeat
返回一个平坦的数组,因此使用了
numpy.reformate
。看来
repeat
比仅仅广播要快:

%timeit empty_dataset=np.empty(2*2,dtype=my_dtype); empty_dataset[:]=ref_array
100000 loops, best of 3: 9.09 us per loop

%timeit repeat_dataset=np.repeat(ref_array, 2*2).reshape((2,2))
100000 loops, best of 3: 5.92 us per loop