【问题标题】:numpy.getbuffer causes AttributeError: 'module' object has no attribute 'getbuffer'numpy.getbuffer 导致 AttributeError: 'module' 对象没有属性 'getbuffer'
【发布时间】:2014-03-16 06:35:37
【问题描述】:

我想从 Python 3 中的 numpy 数组中获取缓冲区。 我找到了以下代码:

$ python3
Python 3.2.3 (default, Sep 25 2013, 18:25:56) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> a = numpy.arange(10)
>>> numpy.getbuffer(a)

但是它在最后一步产生错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'getbuffer'

为什么我做错了? 该代码适用于 Python 2。 我使用的 numpy 版本是 1.6.1。

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    根据Developer notes on the transition to Python 3

    PyBuffer(对象)

    由于 Py3 中有一个本地缓冲区对象,memoryview,所以 newbuffergetbuffer 函数从 Py3 中的多数组中删除: 它们的功能由新的 memoryview 对象接管。

    >>> import numpy
    >>> a = numpy.arange(10)
    >>> memoryview(a)
    <memory at 0xb60ae094>
    >>> m = _
    >>> m[0] = 9
    >>> a
    array([9, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    

    【讨论】:

      【解决方案2】:

      Numpy 的arr.tobytes() 在返回bytes 对象方面似乎比bytes(memoryview(arr)) 快得多。 所以,你可能也想看看tobytes()

      Profiling 用于 Intel i7 CPU、CPython v3.5.0、numpy v1.10.1 上的 Windows 7。

      编辑注意:在 Ubuntu 16.04、Intel i7 CPU、CPython v3.6.5、numpy v1.14.5 上的结果顺序相同。)

      setup = '''import numpy as np; x = np.random.random(n).reshape(n//10, -1)'''
      

      结果

      globals: {'n': 100}, tested 1e+06 times
      
         time (s) speedup                  methods
      0  0.163005   6.03x              x.tobytes()
      1  0.491887   2.00x         x.data.tobytes()
      2  0.598286   1.64x  memoryview(x).tobytes()
      3  0.964653   1.02x            bytes(x.data)
      4  0.982743             bytes(memoryview(x))
      
      
      globals: {'n': 1000}, tested 1e+06 times
      
         time (s) speedup                  methods
      0  0.378260   3.21x              x.tobytes()
      1  0.708204   1.71x         x.data.tobytes()
      2  0.827941   1.47x  memoryview(x).tobytes()
      3  1.189048   1.02x            bytes(x.data)
      4  1.213423             bytes(memoryview(x))
      
      
      globals: {'n': 10000}, tested 1e+06 times
      
         time (s) speedup                  methods
      0  3.393949   1.34x              x.tobytes()
      1  3.739483   1.22x         x.data.tobytes()
      2  4.033783   1.13x  memoryview(x).tobytes()
      3  4.469730   1.02x            bytes(x.data)
      4  4.543620             bytes(memoryview(x))
      

      【讨论】:

        猜你喜欢
        • 2021-01-15
        • 2015-05-16
        • 1970-01-01
        • 2022-12-20
        • 2018-01-14
        • 2014-08-15
        • 2016-07-17
        • 2015-05-26
        • 2016-02-07
        相关资源
        最近更新 更多