Embed a small NumPy array into a predefined block of a large NumPy array

In this tutorial, we will learn how can we embed a small NumPy array into a predefined block of a large NumPy array? By Pranit Sharma Last updated : April 10, 2023

Suppose that we are given a small NxN array arr that we want to embed into a specified region (i.e., a diagonal region) of a large array large.

How to embed a small array into a predefined block of a large array?

To embed a small array into a predefined block of a large array, we simply define the row and column coordinates and then apply multidimensional indexing on the large array using the small array arr and arrange this array according to the row and column coordinates.

Let us understand with the help of an example,

Python code for embedding to a small NumPy array into a predefined block of a large NumPy array

# Import numpy
import numpy as np

# Creating a large array
large = np.zeros((10,10))

# Display large array
print("Large array:\n",large,"\n")

# Creating a small array
arr = np.arange(1,7).reshape(2,3)

# Display small array
print("Small array:\n",arr,"\n")

# Defining row and column coordinates
row = 2
col = 3

# Embedding arr into large
large[row:row+arr.shape[0], col:col+arr.shape[1]] = arr

# Display modified large array
print("Modified Large array:\n",large)

Output

Large array:
 [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] 

Small array:
 [[1 2 3]
 [4 5 6]] 

Modified Large array:
 [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 2. 3. 0. 0. 0. 0.]
 [0. 0. 0. 4. 5. 6. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

Output Screenshot

Embed a small array into a large array | Output

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






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