Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the size of an ndarray not fixed?

The numpy.ndarray documentation states that:

An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size.

I'm surprised by the adjective usually here. I thought an ndarray is always of a fixed size. When is the size of an ndarray not fixed?

like image 964
gerrit Avatar asked Sep 07 '25 14:09

gerrit


2 Answers

You can change the size of an ndarray, using ndarray.resize. I haven't used it extensively, so I can't speak to advantages or disadvantages. However, it seems pretty simple

>>> a = ones(3)

>>> a.resize(1)

>>> a
array([ 1.])

However, it seems to raise errors quite frequently

>>> a.resize(3)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-34-bc3af9ce5259> in <module>()
----> 1 a.resize(3)

ValueError: cannot resize an array that references or is referenced
by another array in this way.  Use the resize function

These can be suppressed by passing in refcheck=False. This tells numpy that you know what you're doing and it doesn't need to check that no other objects are using the same memory. Naturally, this could cause problems if that isn't the case.

>>> a.resize(3, refcheck=False)

>>> a
array([ 1.,  0.,  0.])

>>> a.resize((2, 2), refcheck=False)

>>> a
Out[39]: 
array([[ 1.,  0.],
       [ 0.,  0.]])
like image 138
user2699 Avatar answered Sep 09 '25 08:09

user2699


You are allowed to reshape the dimensions, so the memory itself is fixed-sized, but the way you shape it may be adapted (hence it may not be fixed dimensions).

You can resize the array with resize, but it's basically a new array.

like image 27
Matthieu Brucher Avatar answered Sep 09 '25 08:09

Matthieu Brucher