如何使用np.dtype或类似方法在numpy中创建数组数据类型?

时间:2019-05-07 03:23:48

标签: python numpy numpy-ndarray typing

所以我有4D ndarray,其中每个元素都是数据类型为np.int8的8x8 numpy数组。我想使用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))])的事情,但到目前为止没有任何效果。

1 个答案:

答案 0 :(得分:0)

假设您的数组实际上是一个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
相关问题