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?
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.]])
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.
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