numpy.getbuffer引起AttributeError:'module'对象没有属性'getbuffer'

11

我想在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。

2个回答

12

根据转换到Python 3的开发者笔记

PyBuffer (对象)

由于Py3中有原生缓冲区对象memoryview,因此在Py3中从multiarray中删除了newbuffergetbuffer函数:它们的功能已被新的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])

8
Numpy的arr.tobytes()在返回bytes对象方面似乎比bytes(memoryview(arr))快得多。因此,您可能也需要查看tobytes()
针对Windows 7上的Intel i7 CPU、CPython v3.5.0和numpy v1.10.1进行分析
编辑注意:在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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接