📜  Python| Numpy ndarray.__copy__()(1)

📅  最后修改于: 2023-12-03 14:46:21.246000             🧑  作者: Mango

Python | Numpy ndarray.copy()

NumPy is a python library used for working with multi-dimensional arrays and matrices.

One of the most important object types in NumPy is the ndarray (n-dimensional array) object, which can represent arrays of any dimensionality.

ndarray.__copy__() is a method defined in NumPy that returns a shallow copy of an ndarray object. A shallow copy is a new object that references the same memory locations as the original object, so any changes made to the original object will also affect the shallow copy.

The syntax for using ndarray.__copy__() is:

ndarray.__copy__()

Here, the ndarray refers to the ndarray object on which the method is called.

Example:

import numpy as np

arr = np.array([[1, 2], [3, 4]])
arr_copy = arr.__copy__()

arr[0][0] = 5

print("Original Array:\n", arr)
print("Shallow Copy:\n", arr_copy)

Output:

Original Array:
 [[5 2]
  [3 4]]
Shallow Copy:
 [[5 2]
  [3 4]]

In the above example, we create an ndarray object arr and then create a shallow copy of it using arr.__copy__().

Next, we modify one element of the original array arr[0][0]=5. Since arr_copy is a shallow copy of the original object, the change made to arr also affects arr_copy.

We print both the original array and the shallow copy to verify that they are indeed the same.

It is important to note that ndarray.__copy__() returns only a shallow copy of the original object. If you want to make a deep copy of the object (i.e. copy the object as well as all the objects it references recursively), use numpy.copy() instead.

I hope this introduction to ndarray.__copy__() helped you in understanding its usage and importance in NumPy!