【问题标题】:NumPy `fromstring` function works fine in Python 2.7 but returns error in Python 3.7NumPy `fromstring` 函数在 Python 2.7 中运行良好,但在 Python 3.7 中返回错误
【发布时间】:2019-08-17 19:26:02
【问题描述】:

我使用这种语法来转换字节数组数据字(每个样本 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

这是 Python 2.7.14 中data 的内容:

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

我希望在 Python 3.7 中获得相同的结果。

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

【问题讨论】:

  • 什么是scope
  • scope 是一个 activex 对象,需要从仪器接收二进制向量。在 python 2.7.14 中,数据字被定义为二进制数组:缓冲区:��P��������0����@�p��p����...... ..
  • python 3.7:在 LIclipse 的变量选项卡中,我可以看到 dataword 被定义为 memoryview:

标签: python arrays python-2.7 numpy python-3.7


【解决方案1】:

简单的解决方案...发现阅读 numpy 手册:用 frombuffer 替换 fromstring

data = numpy.frombuffer(dataword, dtype=numpy.int16) 完美运行

【讨论】:

  • 谢谢毛里齐奥
【解决方案2】:

TypeError 试图告诉您 dataword 属于不受支持的类型 memoryview
它需要作为不可变类型传递,例如bytes

data = numpy.fromstring(dataword.tobytes(), dtype=numpy.int16)

更好; scope 似乎是一个类似文件的对象,所以这也可以工作:

data = numpy.fromfile(scope, dtype=numpy.int16, count=rlen//2-4)

【讨论】:

  • 明白了,一切都基于python3如何处理二进制字符串。我相信这会奏效,我会尝试给你一个答案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
相关资源
最近更新 更多