英文:
Overwriting Numpy Array Memory In-Place
问题
I am looking for validation that overwriting a numpy array with numpy.zeros
overwrites the array at the location(s) in memory where the original array's elements are stored.
英文:
I am looking for validation that overwriting a numpy array with numpy.zeros
overwrites the array at the location(s) in memory where the original array's elements are stored.
The documentation discusses this, but it seems I don't have enough background to understand whether just setting new values with the zeros function will overwrite the location in-place. One question asked here appears to indicate that it does. On the other hand, if I am interpreting the answer to this question correctly, it may not.
答案1
得分: 1
无法使用numpy.zeros
来覆盖现有NumPy数组的内存。numpy.zeros
不提供此功能。如果您认为正在这样做,您很可能有这样的代码:
existing_array_name = numpy.zeros(...)
这并不会清除现有数组的内存,而是创建一个新的数组。
如果要将数组的元素置零,可以使用以下方法:
array[...] = 0
参考一下,NumPy函数通常通过将该数组作为out
参数来允许覆盖现有数组的内存。例如,您可以将两个数组a
和b
的元素相加,并将结果写入现有数组c
,方法如下:
numpy.add(a, b, out=c)
英文:
There is no way to overwrite an existing NumPy array's memory with numpy.zeros
. numpy.zeros
does not offer such functionality. If you thought you were doing that, you most likely had code like
existing_array_name = numpy.zeros(...)
which does not clear the existing array's memory. It creates a new array.
If you want to zero out an array's elements, use
array[...] = 0
For reference, NumPy functions that do let you overwrite an existing array's memory usually do so by taking that array as an out
parameter. For example, you can add the elements of two arrays a
and b
and write the result into an existing array c
by doing
numpy.add(a, b, out=c)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论