2014-02-17 9 views
5

Ich möchte in Python einen Puffer von einem numpy Array bekommen 3. ich den folgenden Code gefunden habe:numpy.getbuffer Attribute verursacht: ‚Modul‘ Objekt hat kein Attribut ‚GetBuffer‘

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

aber es erzeugt den Fehler im letzten Schritt:

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

Warum mache ich falsch? Der Code funktioniert gut für Python 2. Die numpy Version, die ich benutze, ist 1.6.1.

Antwort

6

Nach Developer notes on the transition to Python 3:

PyBuffer (object)

Since there is a native buffer object in Py3, the memoryview , the newbuffer and getbuffer functions are removed from multiarray in Py3: their functionality is taken over by the new memoryview object.

>>> 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]) 
3

Numpy des arr.tobytes() scheint schneller zu sein als deutlich bytes(memoryview(arr)) in einem bytes Objekt zurück. Sie können also auch tobytes() betrachten.

Profilerstellung für Windows 7 auf Intel i7 CPU, CPython v3.5.0, numpy v1.10.1.

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

Ergebnisse

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)) 
Verwandte Themen