本文介绍了numpy frombuffer-AttributeError:"str"对象没有属性"__buffer__"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python版本:3.5.2numpy版本:1.12.1

Python Version: 3.5.2Numpy Version : 1.12.1

错误:

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

尝试过的事情

  1. 尝试使用在线Ideone编译器,在Python3.xx中也遇到了相同的错误.
  2. 已引用 scipy常见问题解答用于numpy和python兼容版本,其中指出"NumPy支持Python 2.x系列(版本2.6和 2.7),以及Python 3.2和更高版本.支持Python 3的NumPy的第一个版本是NumPy 1.5.0."
  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中解决该错误的任何建议或线索.

Can't figure out the issue, tried stackoverflow for same issue but nothing found, may be i had missed it.Any suggestions or leads on why the error and how to resolve it in python3.xx.

推荐答案

在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用于创建和显示字节串.

In PY3, the default string type is unicode. The b is used to create and display bytestrings.

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

The np.frombuffer docs should be updated to reflect the difference. The 'hello world' example only works with PY2 or with PY3 bytestrings.

正如我在评论中指出的那样,关于frombuffer的SO问题很少,表明它很少使用.到目前为止,np.array是创建数组的最常用方法,即使是从字符串开始:

As I noted in the comments, there are few SO questions regarding frombuffer, indicating that it is rarely used. np.array is by far the most common way of making an array, even from strings:

In [80]: np.array('hello')
Out[80]: 
array('hello', 
      dtype='<U5')

或使用list将字符串拆分为字符:

or use list to split the string into characters:

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

I created a bug issue: https://github.com/numpy/numpy/issues/8933

这篇关于numpy frombuffer-AttributeError:"str"对象没有属性"__buffer__"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:47