Let’s say we want to create a NumPy array of a particular shape that is filled with all zeros or all ones. We can do so easily using the numpy.zeros() or numpy.ones() function.
For example, we can use the following Python code to create a NumPy array of shape (2, 3) such that the array is filled with all zeros.
import numpy a = numpy.zeros(shape=(2, 3), dtype=int) print("a: \n", a)
Here, the shape argument of the numpy.zeros() function indicates the shape of the created array. In our case, the shape is (2, 3). So, the created array will have 2 rows and each row will have three elements.
The second argument indicates the data type of the array elements. In our case, the created array will contain integers.
The output of the above program will be:
a: [[0 0 0] [0 0 0]]
On the other hand, we can use the numpy.ones() function in the following way to create a numpy array that is filled with all ones.
import numpy b = numpy.ones(shape=(2, 3), dtype=float) print("b: \n", b)
Here also, the shape argument in the numpy.ones() function indicates the shape of the created array. And the data type indicates the data type of the array elements.
Please note that here we are creating a NumPy array with the shape (2, 3). So, the array will have 2 rows and each row will have 3 elements. And the created array elements will be floats.
The output of the mentioned program will be:
b: [[1. 1. 1.] [1. 1. 1.]]
0 Comments