The numpy.full
function is a powerful tool in the NumPy library that creates a new array with a specified shape and fills it with a constant value.
Syntax
numpy.full(shape, fill_value, dtype=None, order='C')
shape
: The shape of the output array. This can be a single integer or a sequence of integers.fill_value
: The constant value to fill the array with.dtype
(optional): The data type of the output array. If not specified, it will default toNone
and NumPy will automatically determine the data type based on thefill_value
parameter.order
(optional): Specifies the memory layout of the array. It can be either'C'
(row-major) or'F'
(column-major). The default is'C'
.
Usage Examples
Let’s explore some examples to understand how the numpy.full
function works.
Example 1: Creating a 1D Array
import numpy as np
a = np.full(5, 3)
print(a)
Output:
array([3, 3, 3, 3, 3])
In this example, we create a 1-dimensional array of size 5 and fill it with the value 3. The resulting array [3, 3, 3, 3, 3]
is printed.
Example 2: Creating a 2D Array
import numpy as np
b = np.full((3, 2), 5, dtype=float)
print(b)
Output:
array([[5., 5.],
[5., 5.],
[5., 5.]])
In this example, we create a 2-dimensional array of shape (3, 2)
and fill it with the value 5. The data type of the array is explicitly set to float
using the dtype
parameter. The resulting array is printed.
Example 3: Creating an Array with a Different Memory Layout
import numpy as np
c = np.full((2, 2), 7, order='F')
print(c)
Output:
array([[7, 7],
[7, 7]])
In this example, we create a 2-dimensional array of shape (2, 2)
and fill it with the value 7. The order
parameter is set to 'F'
, which specifies a column-major memory layout. The resulting array is printed.
Conclusion
The numpy.full
function is a versatile tool for creating new arrays with a constant value. It allows you to specify the shape, fill value, data type, and memory layout of the resulting array. Understanding how to use this function will greatly enhance your data manipulation capabilities with the NumPy library.