【问题标题】:numpy frombuffer - AttributeError: 'str' object has no attribute '__buffer__'numpy frombuffer - AttributeError:'str'对象没有属性'__buffer__'
【发布时间】:2017-04-12 07:25:14
【问题描述】:

Python 版本:3.5.2 Numpy 版本:1.12.1

错误:

import numpy as np
s = 'Hello World'
np.frombuffer(s, dtype='S1')
AttributeError: 'str' object has no attribute '__buffer__'

尝试过的事情:

  1. 试过在线 Ideone 编译器,在 Python3.xx 中遇到同样的错误。
  2. 引用 scipy faqs 以获得 numpy 和 python 兼容版本,其中指出“NumPy 支持 Python 2.x 系列,(版本 2.6 和 2.7),以及 Python 3.2 和更新版本。第一个支持 Python 3 的 NumPy 版本是 NumPy 1.5.0。”

无法解决问题,尝试 stackoverflow 解决同样的问题但没有找到,可能是我错过了它。 关于错误原因以及如何在 python3.xx 中解决它的任何建议或线索。

【问题讨论】:

  • 所以起初我觉得哦.. 这是一个简单的 Dtype 错误。然后我尝试了,然后我更加努力。现在我很焦虑。
  • 字符串不是缓冲区,尤其是在字符串是 unicode 的 py3 中。你想要什么数组?你为什么使用frombuffer?这不是初学者工具。
  • frombuffer docs 有一个这样的例子,但需要对它进行改进以供 py3 使用。
  • stackoverflow.com/q/22236749 是唯一相关的 SO 问题,表明 frombuffer 是多么罕见和专业。将s 创建为字节串可能会起作用。我不能从这里测试。
  • @hpaulj 感谢您提供宝贵的 cmets 和链接。初学者通常从文档开始,这是我为了了解 frombuffer 并变得更加了解该主题而采取的方式。

标签: python-3.x numpy


【解决方案1】:

在 PY3 会话中:

In [62]: np.frombuffer('hello world')
...
AttributeError: 'str' object has no attribute '__buffer__'
In [63]: np.frombuffer(b'hello world')
...
ValueError: buffer size must be a multiple of element size
In [64]: np.frombuffer(b'hello world',dtype='S1')
Out[64]: 
array([b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd'],  dtype='|S1')

在 PY3 中,默认的字符串类型是 unicode。 b 用于创建和显示字节串。

np.frombuffer 文档应更新以反映差异。 'hello world' 示例仅适用于 PY2 或 PY3 字节串。

正如我在 cmets 中指出的,关于 frombuffer 的 SO 问题很少,表明它很少使用。 np.array 是目前为止最常用的创建数组的方法,即使是字符串:

In [80]: np.array('hello')
Out[80]: 
array('hello', 
      dtype='<U5')

或使用list将字符串拆分为字符:

In [81]: np.array(list('hello'))
Out[81]: 
array(['h', 'e', 'l', 'l', 'o'], 
      dtype='<U1')

In [82]: np.array(b'hello')
Out[82]: 
array(b'hello', 
      dtype='|S5')
In [83]: np.array(list(b'hello'))
Out[83]: array([104, 101, 108, 108, 111])

In [85]: np.fromiter('hello','S1')
Out[85]: 
array([b'h', b'e', b'l', b'l', b'o'], 
      dtype='|S1')
In [86]: np.fromiter('hello','U1')
Out[86]: 
array(['h', 'e', 'l', 'l', 'o'], 
      dtype='<U1')*

我创建了一个错误问题:https://github.com/numpy/numpy/issues/8933

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2021-10-04
    • 2019-12-02
    • 2021-09-25
    • 2014-03-04
    • 2013-09-22
    相关资源
    最近更新 更多