NumPy Copies and ViewsThe copy of an input array is physically stored at some other location and the content stored at that particular location is returned which is the copy of the input array whereas the different view of the same memory location is returned in the case of view. In this section of the tutorial, we will consider the way by which, the different copies and views are generated from some memory location. Array AssignmentThe assignment of a numpy array to another array doesn't make the direct copy of the original array, instead, it makes another array with the same content and same id. It represents the reference to the original array. Changes made on this reference are also reflected in the original array. The id() function returns the universal identifier of the array similar to the pointer in C. Consider the following example. ExampleOutput: Original Array: [[ 1 2 3 4] [ 9 0 2 3] [ 1 2 3 19]] ID of array a: 139663602288640 making copy of the array a ID of b: 139663602288640 Changes on b also reflect to a: [[ 1 2 3] [ 4 9 0] [ 2 3 1] [ 2 3 19]] ndarray.view() methodThe ndarray.view() method returns the new array object which contains the same content as the original array does. Since it is a new array object, changes made on this object do not reflect the original array. Consider the following example. ExampleOutput: Original Array: [[ 1 2 3 4] [ 9 0 2 3] [ 1 2 3 19]] ID of array a: 140280414447456 ID of b: 140280287000656 printing the view b [[ 1 2 3 4] [ 9 0 2 3] [ 1 2 3 19]] Changes made to the view b do not reflect a Original array [[ 1 2 3 4] [ 9 0 2 3] [ 1 2 3 19]] view [[ 1 2 3] [ 4 9 0] [ 2 3 1] [ 2 3 19]] ndarray.copy() methodIt returns the deep copy of the original array which doesn't share any memory with the original array. The modification made to the deep copy of the original array doesn't reflect the original array. Consider the following example. ExampleOutput: Original Array: [[ 1 2 3 4] [ 9 0 2 3] [ 1 2 3 19]] ID of array a: 139895697586176 ID of b: 139895570139296 printing the deep copy b [[ 1 2 3 4] [ 9 0 2 3] [ 1 2 3 19]] Changes made to the copy b do not reflect a Original array [[ 1 2 3 4] [ 9 0 2 3] [ 1 2 3 19]] Copy [[ 1 2 3] [ 4 9 0] [ 2 3 1] [ 2 3 19]] Next TopicNumPy Matrix Library |