numpy.ones() and numpy.ones_like() in Python

In this tutorial we will understand numpy.ones() and numpy.ones_like() in detail. We will understand the difference between them and also how to implement each of them with all the parameters in Python.

numpy.ones()

numpy.ones(shape, dtype = None, order = ‘C’) : As the name suggests this function returns an array of ones. It takes shape of the required array, dtype(optional) and order to create an array of ones.

The default parameters of numpy.ones() are :

  • shape: shape is one of the main parameter of numpy.ones(). It is generally an integer or sequence of integers which determine the shape of the required array.
  • dtype: dtype is one of the optional parameter of numpy.ones(). It determines the data type of the returned array. By default it is of float data type.
  • order: It is of two type: C_continuous and F_continuous. ‘C’ means to index the elements in row-major order whereas ‘F’ means to index the elements in column-major order in the memory.
import numpy as np
print("Case 1:\n", np.ones([4,4]))
print("Case 2:\n", np.ones([4,4],dtype=int))

Output :

Case 1:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

Case 2:
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

numpy.ones_like()

numpy.ones_like(a, dtype = None, order = ‘K’, subok = True, shape=None) : This function is slightly different from numpy.ones(). Instead of taking a shape this function takes an array a, and returns the new array of ones of given shape and type as given array.

The default parameters of numpy.ones_like() are :

  • array(a): An array according to which (or similar to which) the new array of ones is to be created.
  • dtype: It determines the data type of the returned array. By default it is of float data type.
  • order: It is of two type: C_continuous and F_continuous. ‘C’ means to index the elements in row-major order whereas ‘F’ means to index the elements in column-major order in the memory.
  • subok: If true, then newly created array will be sub-class of array given otherwise it will be a base-class array.
  • shape: It is generally an integer or sequence of integers that are used to override the shape of the result.
import numpy as np
a=np.random.rand(3,2)
print(a)
print(np.ones_like(a,int))
[[0.95447352 0.87079604]
[0.96982549 0.79796688]
[0.29944925 0.65976334]]

[[1 1]
[1 1]
[1 1]]

Leave a Reply