How to create an empty and a full NumPy array
Creating arrays is a basic operation in NumPy. Two commonly used types are:
- Empty array: This array isn’t initialized with any specific values. It’s like a blank page, ready to be filled with data later. However, it will contain random leftover values in memory until you update it.
- Full array: This is an array where all the elements are set to the same specific value right from the start. It’s like a sheet filled with one number everywhere.
Now let’s understand how to create an empty array and a full array in detail.
Creating Empty Array
Creating an empty array is useful when you need a placeholder for future data that will be populated later. It allocates space without initializing it, which can be efficient in terms of performance.
- Use np.empty() function.
- Specify the shape of the array as a tuple.
- Optionally, define the data type using the dtype parameter.
Syntax:
numpy.empty(shape, dtype=float, order='C')
Parameters:
- shape (tuple of int): Shape of the new array
- dtype (data-type, optional): data type of the array (default is float).
- order ({'C', 'F'}, optional): Memory layout. 'C' means row-major (C-style), 'F' means column-major (Fortran-style).
Example: This code creates a 3x4 empty array using np.empty().
import numpy as np
empArr = np.empty((3, 4))
print(empArr)
Output
[[4.68337834e-310 0.00000000e+000 0.00000000e+000 0.00000000e+000] [0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000] [0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000]...
Explanation:
- np.empty((3, 4)): Creates an array with shape (3,4).
- The values are uninitialized garbage values (whatever is present in memory).
- This is faster than creating an array filled with zeros or ones, but you should assign values before using it.
Creating Full Array
A full array is ideal when you need an array initialized with a specific value, such as zeros or ones, which is common in many mathematical computations.
- Use np.full() function.
- Pass the desired shape and fill value.
- Optionally, specify the data type.
Syntax:
numpy.full(shape, fill_value, dtype=None, order='C')
Parameters:
- shape (tuple of int): Shape of the new array.
- fill_value (scalar): The constant value to fill the array with.
- dtype (data-type, optional): data type of the array (inferred if not given).
- order ({'C', 'F'}, optional): Memory layout.
Example: This code creates a 3x4 array filled with the value 5 using np.full().
import numpy as np
fullArr = np.full((3, 4), 5)
print(fullArr)
Output
[[5 5 5 5] [5 5 5 5] [5 5 5 5]]
Explanation:
- np.full((3, 4), 5): Creates an array of shape (3,4) where every element is 5.
- Unlike np.empty(), this array is fully initialized with the given value.
- Useful when you need a matrix with constant values for calculations.