首页 > 解决方案 > 如何使用 np.dtype 或类似的东西在 numpy 中创建数组数据类型?

问题描述

所以我有 4D ndarray,其中每个元素都是一个 8x8 numpy 数组,数据类型为 np.int8。我想用来tobytes()将其转换为位串,然后frombuffer()将其转换回其原始状态。如何创建一个数据类型dt,以便np.frombuffer(bits, dtype=dt)在重塑后将原始 ndarray 归还给我?按照此处的文档

https://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html#numpy.dtype

我已经尝试了很多东西,dt = np.dtype([('block', np.int8, (8x8))])但到目前为止没有任何效果。

标签: pythonnumpynumpy-ndarraytyping

解决方案


假设您的数组实际上是一个 6D 数组,其中每个元素都是一个 np.int8,您可以这样做:

arr = np.random.randint(-100, 100, (2, 3, 2, 3, 8, 8)).astype(np.int8)
print(arr.shape)
print(arr.dtype)
arr_bytes = arr.tobytes()
arr_reborn = np.frombuffer(arr_bytes, dtype=np.int8).reshape(arr.shape)
print(np.all(arr == arr_reborn))

印刷

>>> (2, 3, 2, 3, 8, 8)
>>> int8
>>> True

推荐阅读