解决:numpy frombuffer - AttributeError: 'str' object has no attribute '__buffer__'

错误:

Python Version: 3.5.2 Numpy Version : 1.12.1

Error:

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

Things Tried:

  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."

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.


解决;

n a PY3 session:

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

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

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

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

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

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

参考:https://stackoverflow.com/questions/43362986/numpy-frombuffer-attributeerror-str-object-has-no-attribute-buffer
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值