Numpy frombuffer - AttributeError: object 'str' does not have attribute '__buffer__'

Python Version: 3.5.2 Printable Version: 1.12.1

Error:

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

Attempts:

  • The Tried Online Ideone compiler got the same error in Python3.xx.
  • Abstract scipy faqs for the version with support for python and numpy, which states: "NumPy supports Python 2.x series (2.6 and 2.7), as well as Python 3.2 and later, the first release to support NumPy Python 3 was NumPy 1.5.0..

I can not understand the problem, I tried stackoverflow for the same problem, but nothing was found, maybe I missed it. Any suggestions or conclusions about why the error is and how to solve it in python3.xx.

+4
source share
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 .

, SO frombuffer, , . 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

+3

Source: https://habr.com/ru/post/1674633/


All Articles