覆盖 Numpy 数组内存(In-Place)

huangapple go评论56阅读模式
英文:

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参数来允许覆盖现有数组的内存。例如,您可以将两个数组ab的元素相加,并将结果写入现有数组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)

huangapple
  • 本文由 发表于 2023年4月10日 23:50:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定