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?
B = AB[:] = A(same asB[:]=A[:]?)numpy.copy(B, A)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
All three versions do different things:
-
B = AThis binds a new name
Bto the existing object already namedA. Afterwards they refer to the same object, so if you modify one in place, you’ll see the change through the other one too. -
B[:] = A(same asB[:]=A[:]?)This copies the values from
Ainto an existing arrayB. The two arrays must have the same shape for this to work.B[:] = A[:]does the same thing (butB = A[:]would do something more like 1). -
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 theBarray. If there were no other references to the previousBvalue, 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?
Method 2
B=Acreates a referenceB[:]=Amakes a copynumpy.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)
Method 3
This is the only working answer for me:
B=numpy.array(A)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0