What is the numpy array.copy() method in Python?
Overview
The array.copy() method in numpy is used to make and change an original array, and returns the two arrays.
Syntax
array.copy()
Parameters
The array.copy() method does not take any parameters.
Return value
The array.copy() method returns both the original and the modified array.
Example
from numpy import array# creating an arraymy_array = array([1, 2, 3, 4, 5])# using the array.copy() methodnew_array = my_array.copy()# changing the 0 index of the arraymy_array[0] = 9print(my_array)print(new_array)
Explanation
- Line 1: We import
arrayfromnumpymodule. - Line 4: We use the
array()method to create an array and assign its value to a variablemy_array. - Line 7: We use the
array.copy()method to copy the array,my_array, to a new array,new_array. - Line 10: We change the index
0value of the arraymy_arrayto9. - Line 11: We print the variable
my_array. - Line 12: we print the variable
new_array.
Note: The
array.copy()method saves the old array even after it is modified.