a shot of dev knowledge

RELATED TAGS

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

Overview

The numpy.ones() function in Python is used to return an array filled with ones (1).

Syntax

numpy.ones(shape, dtype=None, order='C', *, like=None)

Parameters

The numpy.ones() method takes the following parameters:

  • shape: This represents the shape of the new array.
  • dtype: This represents the data type of array you want. This is optional.
  • order: This represents whether to store multi-dimensional data in C or F style. The default is C style. This is optional.
  • like: This represents the array_like object or prototype.

Return value

The numpy.ones() function returns an array with the given shape, dtype, and filled with ones.

Example

import numpy as np

# an aray with 5 ones and integer data type
myarray = np.ones((5), dtype = int)

print(myarray)

Explanation

  • Line 1: We import the numpy model.
  • Line 4: We use the numpy.ones() function to create an array with 5 ones. The data type of the array elements is integer. The output is stored in a variable myarray.
  • Line 6: We print the array myarray.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring