初学python库遇到的问题——解决:numpy frombuffer - AttributeError: 'str' object has no attribute '__buffer__'

最近刚学习完python的基础语法,根据所列的python学习计划,学习完Python基础语法,就要学习python库,主要包含三个,即:

  • Python库-numpy
  • Python库-pandas
  • Python库-matplotlib

目前刚转战到numpy,是根据网上的博客在学习,目前遇到的问题是在执行numpy中的.frombuffer相关代码,例:

  1. import numpy as np

  2. s = 'Hello World'

  3. a = np.frombuffer(s, dtype = 'S1')

  4. print(a)

遇到了如下问题:

traceback (most recent call last):
  File "D:/pyworkspace/bag learn/item.py", line 11, in
    a = np.frombuffer(s, dtype='S1', offset=1)
AttributeError: 'str' object has no attribute '__buffer__'

找到的解决办法是在字符串前面加上b,在PY3中,默认字符串类型是unicode。 b用于创建和显示字节串。

将第2行前面变为s = b'Hello World'就可以了,或者使用list来切分字符串,如下:

 

  1. In [81]: np.array(list('hello'))

  2. Out[81]:

  3. array(['h', 'e', 'l', 'l', 'o'],dtype='

  4.  
  5. In [82]: np.array(b'hello')

  6. Out[82]:

  7.  

  8. array(b'hello',dtype='|S5')

  9. In [83]: np.array(list(b'hello'))

  10. Out[83]: array([104, 101, 108, 108, 111])

  11. In [85]: np.fromiter('hello','S1')

  12. Out[85]:

  13. array([b'h', b'e', b'l', b'l', b'o'],dtype='|S1')

  14. In [86]: np.fromiter('hello','U1')

  15. Out[86]:

  16. array(['h', 'e', 'l', 'l', 'o'],dtype='

 

你可能感兴趣的:(python学习)