Create Numpy Array of different shapes & initialize with identical values using numpy.full() in Python

Creating Numpy Array of different shapes & initialize with identical values using numpy.full()

In this article we will see how we can create a numpy array of different shapes but initialized with identical values. So, let’s start the explore the concept to understand it well.

numpy.full() :

Numpy module provides a function numpy.full() to create a numpy array of given shape and initialized with a given value.

Syntax : numpy.full(shape, given_value, dtype=None, order='C')

Where,

  • shape : Represents shape of the array.
  • given_value : Represents initialization value.
  • dtype : Represents the datatype of elements(Optional).

But to use Numpy we have to include the following module i.e.

import numpy as np
Let’s see the below example to understand the concept.

Example-1 : Create a 1D Numpy Array of length 8 and all elements initialized with value 2

Here array length is 8 and array elements are to be initialized with 2.

Let’s see the below the program.

import numpy as np
# 1D Numpy Array created of length 8 & all elements initialized with value 2
sample_arr = np.full(8,2)
print(sample_arr)
Output :
[2 2 2 2 2 2 2 2]

Example-2 : Create a 2D Numpy Array of 3 rows | 4 columns and all elements initialized with value 5

Here 2D array of row 3 and column 4 and array elements to be initialized with 5.

Let’s see the below the program.

import numpy as np
#Create a 2D Numpy Array of 3 rows & 4 columns. All intialized with value 5
sample_arr = np.full((3,4), 5)
print(sample_arr)
Output :
[[5 5 5 5]
[5 5 5 5]
[5 5 5 5]]

Example-3 : Create a 3D Numpy Array of shape (3,3,4) & all elements initialized with value 1

Here initialized value is 1.

Let’s see the below the program.

import numpy as np
# Create a 3D Numpy array & all elements initialized with value 1
sample_arr = np.full((3,3,4), 1)
print(sample_arr)
Output :

[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]

Example-4 : Create initialized Numpy array of specified data type

Here, array length is 8 and value is 4 and data type is float.

import numpy as np
# 1D Numpy array craeted & all float elements initialized with value 4
sample_arr = np.full(8, 4, dtype=float)
print(sample_arr)
Output :
[4. 4. 4. 4. 4. 4. 4. 4.]
Read Also: