2017-04-12 87 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

相關問題