![]() |
VOOZH | about |
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.
[1. 1. 1. 1. 1.]
numpy.ones(shape, dtype=None, order='C')
Parameters:
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.
[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
Explanation:
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.
[1 1 1 1]
Explanation: By specifying dtype=int, we ensure that the array is of integer type instead of the default float64.
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).
[[[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: