Python 带副本的 Numpy 数组赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19676538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:21:07  来源:igfitidea点击:

Numpy array assignment with copy

pythonarraysnumpy

提问by mrgloom

For example, if we have a numpyarray A, and we want a numpyarray Bwith the same elements.

例如,如果我们有一个numpy数组A,并且我们想要一个具有相同元素的numpy数组B

What is the difference between the following (see below) methods? When is additional memory allocated, and when is it not?

以下(见下文)方法之间有什么区别?什么时候分配额外的内存,什么时候不分配?

  1. B = A
  2. B[:] = A(same as B[:]=A[:]?)
  3. numpy.copy(B, A)
  1. B = A
  2. B[:] = A(一样B[:]=A[:]?)
  3. numpy.copy(B, A)

采纳答案by Blckknght

All three versions do different things:

所有三个版本都做不同的事情:

  1. B = A

    This binds a new name Bto the existing object already named A. Afterwards they refer to the same object, so if you modify one in place, you'll see the change through the other one too.

  2. B[:] = A(same as B[:]=A[:]?)

    This copies the values from Ainto an existing array B. The two arrays must have the same shape for this to work. B[:] = A[:]does the same thing (but B = A[:]would do something more like 1).

  3. numpy.copy(B, A)

    This is not legal syntax. You probably meant B = numpy.copy(A). This is almost the same as 2, but it creates a new array, rather than reusing the Barray. If there were no other references to the previous Bvalue, the end result would be the same as 2, but it will use more memory temporarily during the copy.

    Or maybe you meant numpy.copyto(B, A), which is legal, and is equivalent to 2?

  1. B = A

    这会将新名称绑定B到已命名的现有对象A。之后它们会引用同一个对象,因此如果您就地修改一个对象,您也会通过另一个对象看到更改。

  2. B[:] = A(一样B[:]=A[:]?)

    这会将值复制A到现有数组中B。这两个数组必须具有相同的形状才能工作。B[:] = A[:]做同样的事情(但B = A[:]会做更像 1 的事情)。

  3. numpy.copy(B, A)

    这不是合法的语法。你可能的意思是B = numpy.copy(A). 这与 2 几乎相同,但它创建了一个新数组,而不是重用该B数组。如果没有其他对前一个B值的引用,则最终结果将与 2 相同,但在复制期间会临时使用更多内存。

    或者你的意思是numpy.copyto(B, A),这是合法的,相当于 2?

回答by Mailerdaimon

  1. B=Acreates a reference
  2. B[:]=Amakes a copy
  3. numpy.copy(B,A)makes a copy
  1. B=A创建参考
  2. B[:]=A复印
  3. numpy.copy(B,A)复印

the last two need additional memory.

最后两个需要额外的内存。

To make a deep copy you need to use B = copy.deepcopy(A)

要制作深拷贝,您需要使用 B = copy.deepcopy(A)

回答by Woeitg

This is the only working answer for me:

这是对我来说唯一有效的答案:

B=numpy.array(A)