Skip to content Skip to sidebar Skip to footer

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 us

Solution 1:

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 calllast)
<ipython-input-34-bc3af9ce5259>in<module>()
----> 1 a.resize(3)

ValueError: cannot resize an array that referencesoris referenced
by another arrayin 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.]])

Solution 2:

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.

Post a Comment for "When Is The Size Of An Ndarray Not Fixed?"