Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
function
communitycreator

What is the numpy.ones_like() function in Python?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In Python, the numpy.ones_like() function is used to return an array of ones, 1, with the same shape as a given array.

Syntax

numpy.ones_like(a, dtype=None, order='K')

Parameter value

The numpy.ones_like() function takes the following parameter values:

  • a: This represents the array_like object or the prototype.
  • dtype: This represents the data type of the result. This parameter is optional.
  • order: This represents the type of order of the memory layout of the result. This is an optional parameter.

Return value

The numpy.ones_like() function returns an array of ones, 1, with the same shape and types as the array_like that is passed to it.

Code example

import numpy as np
# creating an array_like
thisarray = np.arange(4, dtype = int)
# implementing the numpy.ones_like() function
myarray = np.ones_like(thisarray)
# printing the two arrays
print(thisarray)
print(myarray)
Implementing the numpy.ones_like() function

Code explanation

  • Line 1: We import the numpy module.

  • Line 4: We create an array prototype, using the numpy.arange() method. We assign the output to a variable called thisarray.

  • Line 7: We implement the numpy.ones_like() function on thisarray and assign the result to another variable called myarray.

  • Lines 11–12: We print both the prototype thisarray and the modified array myarray.

RELATED TAGS

numpy
python
function
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring