如何解决AttributeError: 'Group' 对象没有属性 'dtype'
我想将单个 hdf5 文件中的数据集组合成一个单独的文件中的一个数据集,但我正在努力设置新数据集的 dtype。我收到错误 AttributeError: 'Group' object has no attribute 'dtype' on the line with ds_0_dtype = h5f1[ds].dtype。下面的代码(基于 stackoverflow 上发布的一些示例代码)
with
h5py.File('xxx_xxx_signals.hdf5','r') as h5f1,\
h5py.File('file2.h5','w') as h5f2 :
for i,ds in enumerate(h5f1.keys()) :
if i == 0:
ds_0 = ds
ds_0_dtype = h5f1[ds].dtype
n_rows = h5f1[ds].shape[0]
n_cols = h5f1[ds].shape[1]
else:
if h5f1[ds].dtype != ds_0_dtype :
print(f'Dset 0:{ds_0}: dtype:{ds_0_dtype}')
print(f'Dset {i}:{ds}: dtype:{h5f1[ds].dtype}')
sys.exit('Error: incompatible dataset dtypes')
if h5f1[ds].shape[0] != n_rows :
print(f'Dset 0:{ds_0}: shape[0]:{n_rows}')
print(f'Dset {i}:{ds}: shape[0]:{h5f1[ds].shape[0]}')
sys.exit('Error: incompatible dataset shape')
n_cols += h5f1[ds].shape[1]
prev_ds = ds
h5f2.create_dataset('ds_xxxx',dtype=ds_0_dtype,shape=(n_rows,n_cols),maxshape=(n_rows,None))
first = 0
for ds in h5f1.keys() :
xfer_arr = h5f1[ds][:]
last = first + xfer_arr.shape[1]
h5f2['ds_xxxx'][:,first:last] = xfer_arr[:]
first = last
解决方法
除了根级别的数据集之外,您可能还有 1 个或多个组。 h5f1.keys()
访问所有节点——可以是数据集或组。您需要添加一个测试来跳过组。您可以通过 isinstance()
逻辑测试执行此操作。像这样:
else:
if not isinstance(h5f1[ds],h5py.Dataset) :
print(f'Node 0:{ds_0}: is not a dataset')
sys.exit('Error: unexpected Group; only Datasets expected')
if h5f1[ds].dtype != ds_0_dtype :
一旦您知道如何识别组,您还可以修改代码以避免将它们复制到第二个文件中。但是,这可能不是您想要的结果。我有一篇关于使用 isinstance()
的扩展 SO 帖子。请参阅此链接:
Is there a way to get datasets in all groups at once in h5py?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。