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.
import numpy as np
arr = np.ones(5)
print(arr)
Output
[1. 1. 1. 1. 1.]
Explanation: np.ones(5) creates a one-dimensional array with 5 elements, and each element is initialized to 1.
Syntax
numpy.ones(shape, dtype=float, order='C')
Parameters:
- shape: Integer or tuple specifying the size of the array.
- dtype (optional): Data type of array elements. Default is float.
- order (optional): Memory layout of the array. 'C' for row-major order and 'F' for column-major order.
Examples
Example 1: This example creates a 2D array with 3 rows and 4 columns. All elements are initialized to one.
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: 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.
import numpy as np
arr = np.ones((2, 3), dtype=int)
print(arr)
Output
[[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.
import numpy as np
arr = np.ones((2, 2, 3))
print(arr)
Output
[[[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.