python - NumPy `fromstring` 函数在 Python 2.7 中运行良好,但在 Python 3.7 中返回错误
问题描述
我使用这种语法来转换字节数组数据字(每个样本 2 个字节):
data = numpy.fromstring(dataword, dtype=numpy.int16)
Python 3.7 中的相同指令返回错误:
TypeError: fromstring() argument 1 must be read-only bytes-like object, not memoryview
dataword = scope.ReadBinary(rlen-4) #dataword is a byte array, each 2 byte is an integer
data = numpy.fromstring(dataword, dtype=numpy.int16)# data is the int16 array
这是data
Python 2.7.14 中的内容:
[-1.41601562 -1.42382812 -1.42578125 ..., 1.66992188 1.65234375 1.671875 ]
我期望使用 Python 3.7 获得相同的结果。
我应该如何numpy.fromstring()
在 3.7 中使用?
解决方案
TypeError
试图告诉你那
是dataword
不支持的类型memoryview
。
它需要作为不可变类型传递,例如bytes
:
data = numpy.fromstring(dataword.tobytes(), dtype=numpy.int16)
更好;它似乎scope
是一个类似文件的对象,所以这也可以工作:
data = numpy.fromfile(scope, dtype=numpy.int16, count=rlen//2-4)
推荐阅读
- amazon-ecs - 容器实例是否可能不是真正的容器?
- c - 在较大函数的“提取方法”重构后测试静态函数
- jquery - 在 Datatable 表列数据中动态禁用按钮
- r - 如何使用 R 将所有相关数据重塑为列
- python - 熊猫如何将一个数据帧的一列作为一行添加到另一个数据帧中
- machine-learning - 网络的嵌入层是什么样的?
- python - 使用将 77gb 文件读入内存以扫描关键字的 python 脚本,代码有效,但我的计算机没有足够的内存
- ios - 如何获取多个 DispatchWorkItems 的取消状态
- python - 在同一图中使用 Matplotlib 更新绘图
- javascript - 替代方案