python - 如何使用 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))])
但到目前为止没有任何效果。
解决方案
假设您的数组实际上是一个 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
推荐阅读
- python - 过滤基于其他相同大小数组的多维数组
- amazon-web-services - 将现有 DynamoDB 表转换为全局表
- android - 我该如何处理这个崩溃?
- vim - 重新映射
休息 vim 中的映射 - tableau-api - 如何将自定义 SQL 与 [其他 jdbc] 一起用于 hdp3.1 上的画面
- postgresql - Postgres 没有这样的接口 'org.freedesktop.DBus.Properties'
- css - 如何使用 CSS 选择器删除标签中的文本(无标签)?
- c# - 如何使用 wpf 后面的代码从本地数据库(sqlite)中删除数据?
- ios - 使用 SwiftyJSON 进行 JSON 初始化期间的内存泄漏
- c# - 如何从 API 反序列化这个 JSON 字符串(数组数组)