2017-04-12 32 views
4

Pythonのバージョンがありません:3.5.2 numpyのバージョン:1.12.1numpyのfrombuffer - はAttributeError: 'str' はオブジェクトが属性 '__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でエラーとその解決方法を教えてください。 PY3セッションで

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

、デフォルトの文字列型は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

関連する問題