python - 什么时候 ndarray 的大小不固定?

标签 python numpy multidimensional-array numpy-ndarray

numpy.ndarray documentation指出:

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

我对这里的形容词通常感到惊讶。我以为 ndarray 总是固定大小的。什么时候 ndarray 的大小不固定?

最佳答案

您可以使用 ndarray.resize 更改 ndarray 的大小. 我没有广泛使用它,所以我不能说优点或缺点。 然而,它看起来很简单

>>> a = ones(3)

>>> a.resize(1)

>>> a
array([ 1.])

然而,它似乎经常引发错误

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

可以通过传入 refcheck=False 来抑制这些。 这告诉 numpy 你知道你在做什么,它不需要检查没有其他对象正在使用相同的内存。当然,如果不是这种情况,这可能会导致问题。

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

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

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

>>> a
Out[39]: 
array([[ 1.,  0.],
       [ 0.,  0.]])

关于python - 什么时候 ndarray 的大小不固定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53614874/

相关文章:

python - 使用正则表达式提取用户的阿拉伯名字

python - 将日期更改为财政月份 pandas python

python - 通过交换维度重组列表并转换为 numpy

python - 不使用 scikit learn 训练测试分割

java 多维数组失败并出现空指针异常

mongodb - 想要在 Mongo 中更新数组对象值的数组

javascript - 如何展平夹紧的阵列

python - 在循环中使用 Scrapy Itemloader

python - 如何使用 Python 捕获输出并同时显示它?

python - np.linspace 和 np.arange 有什么区别?