The purpose of the copy array

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

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

  1. B = A
  2. B[:] = A (same as B[:]=A[:] ?)
  3. numpy.copy(B, A)
+70
python arrays numpy
Oct 30 '13 at 7:44
source share
3 answers

All three versions do different things:

  1. B = A

    This associates the new name B with an existing object already named A After that, they refer to the same object, so if you change one in place, you will see the change through the other.

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

    This copies the values ​​from A to an existing array of B Two arrays must have the same shape for this to work. B[:] = A[:] does the same (but B = A[:] does something more like 1).

  3. numpy.copy(B, A)

    This syntax is not valid. You probably meant B = numpy.copy(A) . This is almost the same as 2, but it creates a new array, and does not reuse array B If there were no other references to the previous value of B , the end result would be the same as 2, but it would temporarily use more memory while copying.

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

+86
Oct 30 '13 at 7:59
source share
  1. B=A creates a link
  2. B[:]=A makes a copy
  3. numpy.copy(B,A) makes a copy

the last two require additional memory.

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

+25
Oct 30 '13 at 7:52
source share

This is the only working answer for me:

 B=numpy.array(A) 
+6
Sep 14 '16 at 16:18
source share



All Articles