Numpy, the array doesn't have its own data?

后端 未结 1 622
清酒与你
清酒与你 2020-12-14 17:34

I tried to use resize on an array in this way:

a = np.array([1,2,3,4,5,6], dtype=np.uint8)
a.resize(4,2)
print a 

and the outp

相关标签:
1条回答
  • 2020-12-14 18:17

    Lets start with the following:

    >>> a = np.array([1,2,3,4,5,6], dtype=np.uint8)
    >>> b = a.reshape(2,3)
    >>> b[0,0] = 5
    >>> a
    array([5, 2, 3, 4, 5, 6], dtype=uint8)
    

    I can see here that array b is not its own array, but simply a view of a (just another way to understand the "OWNDATA" flag). To put it simply both a and b reference the same data in memory, but b is viewing a with a different shape. Calling the resize function like ndarray.resize tries to change the array in place, as b is just a view of a this is not permissible as from the resize definition:

    The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory.


    To circumvent your issue you can call resize from numpy (not as an attribute of a ndarray) which will detect this issue and copy the data automatically:

    >>> np.resize(b,(4,2))
    array([[5, 2],
           [3, 4],
           [5, 6],
           [5, 2]], dtype=uint8)
    

    Edit: As CT Zhu correctly mention np.resize and ndarray.resize add data in two different ways. To reproduce expected behavior as ndarray.resize you would have to do the following:

    >>> c = b.copy()
    >>> c.resize(4,2)
    >>> c
    array([[5, 2],
           [3, 4],
           [5, 6],
           [0, 0]], dtype=uint8)
    
    0 讨论(0)
提交回复
热议问题