Numpy full() Function



The Numpy full() function is used to create a new array with a specified shape and data type, where all elements are initialized to a given value.

The NumPy array created using the numpy.full() function contains the same specified element repeated throughout the array. Numpy arrays of different dimensions, such as 1-D, 2-D, and 3-D, can be created using this function with various data types, including strings, floats, complex and integers.

Syntax

Following is the syntax of the Numpy full() function −

numpy.full(shape, fill_value, dtype=None, order='C', like=None)   

Parameters

Following are the parameters of the Numpy full() function −

  • shape- It can be integer or sequence of integers, used to define the dimensions of the array.
  • fill_value- Specified value to fill the array with.
  • dtype(optional)- By default, the data-type is inferred from the input data. By default, the data-type is float.
  • order(optional)- This represents whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to C.
  • like (optional)- This is the reference object to allow the creation of arrays that are not NumPy arrays

Return Values

This function returns returns the array of given shape, order, and datatype filled with a specified value.

Example

Following is an basic example to create an numpy array with specified value using Numpy full() function −

import numpy as np
# create a 1D array of five 2s
array1 = np.full(5,2)
print('1D Numpy Array: ',array1)
#type of array
print(type(array1))

Output

Following is the output of the above code −

1D Numpy Array:  [2 2 2 2 2]
<class 'numpy.ndarray'>

Example : N-dimensional Array with 'numpy.full()'

We can create a multi-dimentional numpy array of specifed value using numpy.full() function. Here, we have created a numpy 2-D array with a shape of (3,4), and all the elements are filled with the value 24 −

 
# numpy.full method 
import numpy as np 
my_Array = np.full([3,2], 24) 
print("Numpy 2-D Array : \n", my_Array) 

Output

Following is the output of the above code −

Numpy 2-D Array : 
 [[24 24]
 [24 24]
 [24 24]]

Example : Numpy Array of 'string' Datatype

To create a NumPy array with a specified data type (dtype) of string, we can use the dtype parameter in the numpy.full() function. In the following example, we have created a numpy array of str datatype −

import numpy as np
my_Array = np.full([3, 2], fill_value='4', dtype='str')
print("Numpy 2-D Array : \n", my_Array) 

Output

Following is the output of the above code −

Numpy 2-D Array : 
 [['4' '4']
 ['4' '4']
 ['4' '4']]
numpy_array_creation_routines.htm
Advertisements