python - NumPy 调整大小方法

标签 python exception numpy resize

谁能给我解释一下? (Python 3.3.2、numpy 1.7.1):

>>> a = np.array([[1,2],[3,4]])
>>> a    # just a peek
array([[1, 2],
       [3, 4]])
>>> a.resize(3,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot resize an array references or is referenced
by another array in this way.  Use the resize function
>>> a = np.array([[1,2],[3,4]])
>>> a.resize(3,2)
>>> a
array([[1, 2],
       [3, 4],
       [0, 0]])
>>> a = np.array([[1,2],[3,4]])
>>> print(a)   # look properly this time
[[1 2]
 [3 4]]
>>> a.resize(3,2)
>>> a
array([[1, 2],
       [3, 4],
       [0, 0]])

为什么查看数组会创建对它的引用? (或者,至少,为什么在我完成查找后该引用仍然存在?) 另外,是我一个人还是那个异常需要重写一下?

最佳答案

来自documentation (强调我的):

The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.

print 不同,您的“peek”不会在之后减少引用计数。这是因为,在解释器中,最后一次计算的结果被分配给 _。尝试:

print(_) # shows array
a.resize((3, 2), refcheck=False) # works

或者,如果您在两者之间进行任何其他计算(例如只是 1 + 2),这将从 _ 中取消引用您的数组。

关于python - NumPy 调整大小方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730366/

相关文章:

python - 将函数应用于数据框的元素

python - 将 Numpy 数组中最终作为单独数组的所有元素更改为 float Python

python - 如何向 OpenCV 函数 cv.dft() 输入复数值?

python - Django - 需要只能处理年份或年份和月份值的日期时间字段

python - 获取 python 文件或环境的 CURRENT_FILE_ENCODING

java - 转换为 MYSQL 时,java 中线程 "main"java.lang.NullPointerException 出现异常

python - 从异常中获取数据

java - 为什么我得到 NoClassDefFoundError 异常?

python - 将命令行参数从文件夹脚本传递到文件脚本

python - 如何通过 C API 终止 python 脚本