这个答案解决了 OP 在 cmets 中对我的第一个答案的请求(“一个例子是 ds_1 所有列,ds_2 前两列,ds_3 第 4 和 6 列,ds_4 所有列”)。过程非常相似,但输入比第一个答案“稍微复杂一些”。因此,我使用了不同的方法来定义要复制的数据集名称和列。区别:
- 第一个解决方案从“keys()”迭代数据集名称(完全复制每个数据集,附加到新文件中的数据集)。新数据集的大小是通过对所有数据集的大小求和来计算的。
- 第二种解决方案使用 2 个列表来定义 1) 数据集名称 (
ds_list) 和 2) 要从每个数据集中复制的关联列(col_list 是列表中的一个)。新数据集的大小是通过对col_list 中的列数求和来计算的。我使用“花式索引”来提取使用col_list 的列。
- 您决定如何执行此操作取决于您的数据。
- 注意:为简单起见,我删除了 dtype 和 shape 测试。您应该包含这些内容以避免“现实世界”问题的错误。
代码如下:
# Data for file1
arr1 = np.random.random(120).reshape(20,6)
arr2 = np.random.random(120).reshape(20,6)
arr3 = np.random.random(120).reshape(20,6)
arr4 = np.random.random(120).reshape(20,6)
# Create file1 with 4 datasets
with h5py.File('file1.h5','w') as h5f :
h5f.create_dataset('ds_1',data=arr1)
h5f.create_dataset('ds_2',data=arr2)
h5f.create_dataset('ds_3',data=arr3)
h5f.create_dataset('ds_4',data=arr4)
# Open file1 for reading and file2 for writing
with h5py.File('file1.h5','r') as h5f1 , \
h5py.File('file2.h5','w') as h5f2 :
# Loop over datasets in file1 to get dtype and rows (should test compatibility)
for i, ds in enumerate(h5f1.keys()) :
if i == 0:
ds_0_dtype = h5f1[ds].dtype
n_rows = h5f1[ds].shape[0]
break
# Create new empty dataset with appropriate dtype and size
# Use maxshape parameter to make resizable in the future
ds_list = ['ds_1','ds_2','ds_3','ds_4']
col_list =[ [0,1,2,3,4,5], [0,1], [3,5], [0,1,2,3,4,5] ]
n_cols = sum( [ len(c) for c in col_list])
h5f2.create_dataset('combined', dtype=ds_0_dtype, shape=(n_rows,n_cols), maxshape=(n_rows,None))
# Loop over datasets in file1, read data into xfer_arr, and write to file2
first = 0
for ds, cols in zip(ds_list, col_list) :
xfer_arr = h5f1[ds][:,cols]
last = first + xfer_arr.shape[1]
h5f2['combined'][:, first:last] = xfer_arr[:]
first = last