NumPy - Create array filled with all ones
To create an array filled with all ones in Python, NumPy provides the numpy.ones() function. You can specify the shape and data type of the array.
Example: This example creates a simple 1D array of ones with 5 elements.
import numpy as np
arr = np.ones(5)
print(arr)
Output
[1. 1. 1. 1. 1.]
Syntax
numpy.ones(shape, dtype=None, order='C')
Parameters:
- shape (int or tuple): Defines size of array.
- dtype (optional): Sets data type of elements.
- order (optional): Memory layout, 'C' -> Row-wise (default, C-style) and 'F' -> Column-wise (Fortran-style).
2D Array of Ones
We can also create a 2D array (matrix) filled with ones by passing a tuple to the shape parameter.
Example: This example creates a 2D matrix of ones with 3 rows and 4 columns.
import numpy as np
arr = np.ones((3, 4))
print(arr)
Output
[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
Explanation:
- The argument (3, 4) defines the shape of the array.
- The resulting array has 3 rows and 4 columns, filled entirely with 1.0 (float).
Array with a Specific Data Type
We can specify the data type of the array using the dtype parameter.
Example: This example creates a 1D integer array of ones with 4 elements.
import numpy as np
arr = np.ones(4, dtype=int)
print(arr)
Output
[1 1 1 1]
Explanation: By specifying dtype=int, we ensure that the array is of integer type instead of the default float64.
Multi-Dimensional Array of Ones
We can also create a higher-dimensional array (3D or more) by passing a tuple representing the shape.
Example: This example creates a 3D array of ones with shape (2, 3, 4).
import numpy as np
arr = np.ones((2, 3, 4))
print(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.]]]
Explanation:
- The argument (2, 3, 4) creates a 3D array.
- It has 2 blocks, each containing a 3x4 matrix, filled with 1.0.