Copy Values from One Array to Another in NumPy



To copy values from one array to another, broadcasting as necessary, use the numpy.copyto() method in Python Numpy −

  • The 1st parameter is the source array
  • The 2nd parameter is the destination array

The casting parameter 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.

Steps

At first, import the required library −

import numpy as np

Create a 2d array −

arr = np.array([[28, 49, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])

Displaying our array −

print("Array...",arr)

Get the datatype −

print("Array datatype...",arr.dtype)

Get the dimensions of the Array −

print("Array Dimensions...",arr.ndim)

Get the shape of the Array −

print("Our Array Shape...",arr.shape)

Get the number of elements of the Array −

print("Elements in the Array...",arr.size)

The destination −

arrRes = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

To copy values from one array to another, broadcasting as necessary, use the numpy.copyto() method −

res = np.copyto(arr, arrRes) print("Result...",arrRes)

Example

Open Compiler
import numpy as np # Create a 2d array arr = np.array([[28, 49, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]]) # Displaying our array print("Array...",arr) # Get the datatype print("Array datatype...",arr.dtype) # Get the dimensions of the Array print("Array Dimensions...",arr.ndim) # Get the shape of the Array print("Our Array Shape...",arr.shape) # Get the number of elements of the Array print("Elements in the Array...",arr.size) # The destination arrRes = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15,16]] # To copy values from one array to another, broadcasting as necessary, use the numpy.copyto() method in Python Numpy # The 1st parameter is the source array # The 2nd parameter is the destination array res = np.copyto(arr, arrRes) print("Result...",arrRes)

Output

Array...
[[28 49 78 88]
[92 81 98 45]
[22 67 54 69]
[69 80 80 99]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

Result...
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Updated on: 2022-02-17T09:54:47+05:30

974 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements