问题
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?
回答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 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.]])
回答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.
来源:https://stackoverflow.com/questions/53614874/when-is-the-size-of-an-ndarray-not-fixed