d.astype()
返回一个AstypeContext
目的。如果你查看源代码AstypeContext
你会更好地了解正在发生的事情:
class AstypeContext(object):
def __init__(self, dset, dtype):
self._dset = dset
self._dtype = numpy.dtype(dtype)
def __enter__(self):
self._dset._local.astype = self._dtype
def __exit__(self, *args):
self._dset._local.astype = None
当您输入AstypeContext
, the ._local.astype
数据集的属性将更新为新的所需类型,当您退出上下文时,它会更改回其原始值。
因此,您或多或少可以获得您正在寻找的行为,如下所示:
def get_dataset_as_type(d, dtype='float32'):
# creates a new Dataset instance that points to the same HDF5 identifier
d_new = HDF.Dataset(d.id)
# set the ._local.astype attribute to the desired output type
d_new._local.astype = np.dtype(dtype)
return d_new
当你现在读到d_new
, 你会得到float32
numpy 数组返回而不是uint16
:
d = hf.create_dataset('data', data=intdata)
d_new = get_dataset_as_type(d, dtype='float32')
print(d[:])
# array([81, 65, 33, 22, 67, 57, 94, 63, 89, 68], dtype=uint16)
print(d_new[:])
# array([ 81., 65., 33., 22., 67., 57., 94., 63., 89., 68.], dtype=float32)
print(d.dtype, d_new.dtype)
# uint16, uint16
请注意,这不会更新.dtype
的属性d_new
(这似乎是不可变的)。如果您也想更改dtype
属性,您可能需要子类化h5py.Dataset
为了这样做。