Copy values from one array to another in Numpy

NumpyServer Side ProgrammingProgramming

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...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...\n",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("\nResult...\n",arrRes)

Example

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...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nElements in the Array...\n",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("\nResult...\n",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]]
raja
Updated on 17-Feb-2022 09:54:47

Advertisements