2017-04-12 186 views
4

Python版本:3.5.2 numpy的版本:1.12.1numpy的frombuffer - AttributeError的: '海峡' 对象有没有属性 '__buffer__'

错误:

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

事情尝试:

  1. Tried Online Ideone compiler, got same error in Python3.xx.
  2. Referred scipy faqs for numpy and python compatible version, which states "NumPy support the Python 2.x series, (versions 2.6 and 2.7), as well as Python 3.2 and newer. The first release of NumPy to support Python 3 was NumPy 1.5.0."

不能找出问题,尝试相同的问题stackoverflow,但没有发现,可能是我错过了它。 关于为什么错误以及如何在python3.xx中解决它的任何建议或线索。

+0

所以一开始我很喜欢哦..这是一个简单的Dtype错误。然后我试了一下,然后我更加努力地尝试。现在我有焦虑。 – Scheme

+1

字符串不是缓冲区,特别是不在py3中,其中字符串是unicode。你想要什么阵列?你为什么使用'frombuffer'?这不是初学者的工具。 – hpaulj

+0

'frombuffer' docs有这样一个例子,但是它需要为py3的使用进行改进。 – hpaulj

回答

3

在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') 

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

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

正如我在评论中指出的那样,关于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

相关问题