Python - numpy.copyto() Method with Examples

Learn about the numpy.copyto() method in Python, how does it work?
By Pranit Sharma Last updated : December 25, 2023

Python - numpy.copyto() Method

The numpy.cpoyto() method is used to make a copy of all the elements of a numpy array. It copies values from one array to another where broadcasting is necessary.

Syntax of numpy.copyto() Method

Below is the syntax of numpy.copyto() method:

numpy.copyto(dst, src, casting='same_kind', where=True)

Parameters of numpy.copyto() Method

Below are the parameters of numpy.copyto() method:

  • dst: array in which values are copied
  • src: array from which values are copied
  • casting: there are different types of casting commands like 'no', 'equiv', 'safe', 'same_kind', 'unsafe'.

Return Value of numpy.copyto() Method

None. It just copies values from one array to another, broadcasting as necessary

Error

The method may raise a TypeError if the casting rule is violated, and if where is provided, it selects which elements to copy.

The numpy.copyto() Method Examples

Practice the below example to understand the use of numpy.copyto() method:

Example 1: Python program to demonstrate the example of numpy.copyto() Method

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([4, 5, 6])

# Creating another array
arr2 = [1, 2, 3]

# Display original array
print("Original Array:\n",arr,"\n")

# Copying arr1 into arr2
np.copyto(arr,arr2)

# Display result
print("Result:\n",arr)

Output

Example: numpy.copyto() Method with Example

Example 2

# Import numpy
import numpy as np

# Creating two arrays
arr1 = np.array([[10, 20, 30], [40, 50, 60]])
arr2 = [[4, 5, 6], [7, 8, 9]]

# Printing arrays
print("Before using of copyto() method")
print("arr1\n", arr1)
print("arr2\n", arr2)

# Copying
np.copyto(arr1, arr2)

# Printing arrays
print("\nAfter using of copyto() method")
print("arr1\n", arr1)
print("arr2\n", arr2)

Output

Before using of copyto() method
arr1
 [[10 20 30]
 [40 50 60]]
arr2
 [[4, 5, 6], [7, 8, 9]]

After using of copyto() method
arr1
 [[4 5 6]
 [7 8 9]]
arr2
 [[4, 5, 6], [7, 8, 9]]

Web References

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.