w3resource

NumPy: numpy.copyto() function

numpy.copyto() function

The numpy.copyto() function is used to copy values from one array to another, broadcasting as necessary.

The numpy.copyto() function can be useful when we want to copy the values of one array to another array with different dimensions, shapes, or sizes. It provides the flexibility to copy values into the specified output array or a new array can be created and values can be copied. One important thing to note that the function raises a TypeError if the casting rule is violated, and if where is provided, it selects which elements to copy.

Syntax:

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

Parameters:

Name Description Required /
Optional
dst The array into which values are copied. Required
src The array from which values are copied. Required
casting Controls what kind of data casting may occur when copying.
  • 'no' means the data types should not be cast at all.
  • ‘equiv’ means only byte-order changes are allowed.
  • 'safe' means only casts which can preserve values are allowed.
  • same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
  • 'unsafe' means any data conversions may be done.
Optional
where A boolean array which is broadcasted to match the dimensions of dst, and selects elements to copy from src to dst wherever it contains the value True. Optional

Example: Copy the values from one array to another array using numpy.copyto()

import numpy as np

# Creating two numpy arrays of the same shape
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Using copyto() to copy the values from arr1 to arr2
np.copyto(arr2, arr1)

print("arr1: ", arr1)
print("arr2: ", arr2) 

Output:

arr1:  [1 2 3]
arr2:  [1 2 3]

In the above example, the numpy.copyto() function is used to copy values from one array to another (Values from arr1 are copied to arr2).

Example: Copy the values from list to array using numpy.copyto()

import numpy as np

# Creating a numpy array and a Python list
arr1 = np.array([1, 2, 3])
lst = [4, 5, 6]

# Using copyto() to copy the values from lst to arr1
np.copyto(arr1, lst)

print("arr1: ", arr1)

Output:

arr1: [4 5 6]

In the above example, the numpy.copyto() function values from the Python list 'lst' are copied to the 'arr1' numpy array.

Python - NumPy Code Editor:

Previous: NumPy Array manipulation Home
Next: Changing array shape reshape()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/numpy/manipulation/copyto.php