numpy frombuffer - AttributeError:'str'对象没有属性'__buffer__'

JkS*_*haw 10 numpy python-3.x

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__'
Run Code Online (Sandbox Code Playgroud)

事情尝试:

  1. 尝试在线Ideone编译器,在Python3.xx中得到相同的错误.
  2. 称为SciPy的常见问题为numpy的和python兼容版本,其中指出"numpy的支持的Python 2.x的系列,(2.6和2.7版本),以及3.2的Python和更新.NumPy的的第一个版本,以支持Python 3中是NumPy的1.5. 0".

无法弄清楚问题,尝试stackoverflow相同的问题,但没有发现,可能是我错过了它.有关错误的原因以及如何在python3.xx中解决它的任何建议或线索.

hpa*_*ulj 8

在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')
Run Code Online (Sandbox Code Playgroud)

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

np.frombuffer文档应该被更新,以反映不同.该'hello world'示例仅适用于PY2或PY3字节串.

正如我在评论中指出的那样,很少有SO问题frombuffer,表明它很少被使用. np.array到目前为止,这是制作数组的最常用方法,甚至是字符串:

In [80]: np.array('hello')
Out[80]: 
array('hello', 
      dtype='<U5')
Run Code Online (Sandbox Code Playgroud)

或者用于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')*
Run Code Online (Sandbox Code Playgroud)

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