Numpy Array Assignment: Memory Allocation Differences
In NumPy, there are three common ways to assign values to an array:
B = A
When you use B = A, you are not creating a new array. Instead, you are binding a new name (B) to the existing array (A). As a result, any modifications made to one array will be reflected in the other.
B[:] = A
This syntax creates a new array B with the same dimensions and values as A. The original array A is not modified. This method requires less memory allocation compared to numpy.copy.
numpy.copy(B, A)
This method is not legal as you have it written. It should be B = numpy.copy(A). numpy.copy creates a new array B with the same dimensions and values as A. This method requires more memory allocation compared to B[:] = A because it creates a separate physical copy of the data from the original array.
When is Additional Memory Allocated?
Additional memory is allocated when you use numpy.copy to create a new physical copy of the array. This is because it allocates a new contiguous block of memory for the copied data.
When is Memory Not Allocated?
Memory is not allocated when you use B = A because you are simply renaming the original array. Memory is also not allocated when you use B[:] = A because it reuses the same memory location as the original array.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3