首页 > 解决方案 > 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

这是dataPython 2.7.14 中的内容:

[-1.41601562 -1.42382812 -1.42578125 ...,  1.66992188  1.65234375  1.671875  ]

我期望使用 Python 3.7 获得相同的结果。

我应该如何numpy.fromstring()在 3.7 中使用?

标签: pythonarrayspython-2.7numpypython-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)

推荐阅读