带副本的numpy数组分配

问题:带副本的numpy数组分配

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

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

  1. B = A
  2. B[:] = A(与B[:]=A[:]?相同)
  3. numpy.copy(B, A)

For example, if we have a numpy array A, and we want a numpy array B with the same elements.

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)

回答 0

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

  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?

All three versions do different things:

  1. B = A

    This binds a new name B to 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 A into 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 B array. If there were no other references to the previous B value, 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

  1. B=A 创建参考
  2. B[:]=A 复制
  3. numpy.copy(B,A) 复制

后两个需要额外的内存。

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

  1. B=A creates a reference
  2. B[:]=A makes a copy
  3. numpy.copy(B,A) makes a copy

the last two need additional memory.

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


回答 2

这是我唯一的工作答案:

B=numpy.array(A)

This is the only working answer for me:

B=numpy.array(A)