[파이썬][numpy] numpy `full` 함수

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')

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.