What is the purpose of np.ones() in Python?

0205

The np.ones() function in Python, specifically in the NumPy library, is used to create an array filled with ones. You can specify the shape of the array you want to create.

Syntax

numpy.ones(shape, dtype=None)
  • shape: This is a tuple that defines the dimensions of the array.
  • dtype: This is an optional parameter that specifies the desired data type of the array. If not provided, it defaults to float.

Example

Here’s a simple example of how to use np.ones():

import numpy as np

# Create a 2x3 array filled with ones
array_ones = np.ones((2, 3))
print(array_ones)

Output

[[1. 1. 1.]
 [1. 1. 1.]]

This creates a 2-dimensional array with 2 rows and 3 columns, all filled with the value 1.

0 Comments

no data
Be the first to share your comment!