Write the NumPy program to copy data from a given array to another array
In this article, you will learn how to copy data from a given array to another array using the Python NumPy program. NumPy is a Python library used for working with large, multidimensional arrays and matrix. It also provides a large collection of high-level mathematical functions to perform array operations.
The numpy.copy() function is used to copy a numpy array into another. Here is the syntax -
numpy.copy(array, order_type)
It returns an array copy of the given object. The order_type is an optional parameter and of four types {'C', 'F', 'A', 'K'}. It controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if a is Fortran contiguous, otherwise 'C', 'K' means match the layout of 'A' as closely as possible.
NumPy Copy Program
In the following example, we will copy the elements of an array 'x' to another array 'y'.
import numpy as np
# create a numpy array
x = np.array([1, 2, 3, 4, 5, 6])
# copy contents of x to y
y = np.copy(x)
print(y)
It returns the following output -
[1 2 3 4 5 6]
It is important to note that the np.copy() function only creates a shallow copy of an array and will not copy object elements. It is very clear from the given program -
import numpy as np
x = np.array([[4, 12, 10],
[7, 5, 1]])
y = x.copy()
# modify x
x[1, 2] = 24
print('x\n',x)
print('\ny\n',y)
It is clear from the above example that if we have changed the contents of x, the contents of y are unaffected.
Related Articles
Python program to find the median of three valuesMerge sort program in Python
Bubble sort program in Python
Python convert list to numpy array
Python Numpy Array Shape
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Trigonometric functions Python Numpy
Python Pandas Dataframe to CSV
Python Pandas DataFrame
Convert list to dictionary Python
Python dict inside list
Convert dictionary to dataframe Python
Python Pandas CSV to Dataframe
Convert List to Dataframe Python
Python add list to list
Difference between tuple and list in Python
Convert Excel to CSV Python Pandas
Alphabetical order Python
Python | Generate QR Code using pyqrcode module