Can anyone explain this to me? (Python 3.3.2, numpy 1.7.1):
>>> a = np.array([[1,2],[3,4]])
>>> a # just a peek
array([[1, 2],
[3, 4]])
>>> a.resize(3,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot resize an array references or is referenced
by another array in this way. Use the resize function
>>> a = np.array([[1,2],[3,4]])
>>> a.resize(3,2)
>>> a
array([[1, 2],
[3, 4],
[0, 0]])
>>> a = np.array([[1,2],[3,4]])
>>> print(a) # look properly this time
[[1 2]
[3 4]]
>>> a.resize(3,2)
>>> a
array([[1, 2],
[3, 4],
[0, 0]])
Why does taking a peek at the array create a reference to it? (or, at least, why does that reference persist after I'm done looking?) Also, is it just me or does that Exception need a bit of a rewrite?
NumPy: resize() function The resize() function is used to create a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of a. Array to be resized.
With the help of Numpy numpy. resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more.
resize() methods are used to change the size of a NumPy array. The difference between them is that the reshape() does not changes the original array but only returns the changed array, whereas the resize() method returns nothing and directly changes the original array.
Python arrays do not have a resize method, and neither does lists.
From the documentation (emphasis mine):
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. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set
refcheck
toFalse
.
Your "peek", unlike print
, does not decrement the reference count afterwards. This is because, in the interpreter, the result of the last computation is assigned to _
. Try:
print(_) # shows array
a.resize((3, 2), refcheck=False) # works
Alternatively, if you do any other computation (e.g. just 1 + 2
) in-between, this will dereference your array from _
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With