![]() |
VOOZH | about |
numpy.ones() is used to create a NumPy array of a specified shape where all elements are initialized to 1. It is useful when you need an array filled with ones for calculations, testing, or as a starting point for data processing.
Example: The following example creates a 1D array containing 5 ones.
[1. 1. 1. 1. 1.]
Explanation: np.ones(5) creates a one-dimensional array with 5 elements, and each element is initialized to 1.
numpy.ones(shape, dtype=float, order='C')
Parameters:
Example 1: This example creates a 2D array with 3 rows and 4 columns. All elements are initialized to one.
[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
Explanation: np.ones((3, 4)) creates a 2D array with 3 rows and 4 columns filled with 1.
Example 2: This example creates an array of integers instead of the default floating-point values.
[[1 1 1] [1 1 1]]
Explanation: dtype=int argument makes np.ones() create an array of integer values.
Example 3: This example creates a 3D array where all elements are initialized to one.
[[[1. 1. 1.] [1. 1. 1.]] [[1. 1. 1.] [1. 1. 1.]]]
Explanation: np.ones((2, 2, 3)) creates a three-dimensional array with all elements set to 1.