Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy resize method

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?

like image 419
xnx Avatar asked Dec 22 '13 14:12

xnx


People also ask

What is resize in NumPy?

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.

Can NumPy arrays 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.

What is the difference between reshape () and resize ()?

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.

Can I resize an array in Python?

Python arrays do not have a resize method, and neither does lists.


1 Answers

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 to False.

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 _.

like image 70
jonrsharpe Avatar answered Oct 07 '22 21:10

jonrsharpe