Creating an array filled with ones in Python NumPy : np.ones

NumPy’s np.ones is a function used to create a NumPy array filled with ones. Similar to np.zeros, this function is valuable when you need to initialize an array with a specific shape and set all its elements to one. It is a part of the NumPy library, commonly used for numerical and scientific computing in Python.

Usage and purpose:

The primary purpose of np.ones is to create arrays with a predetermined shape and fill them with ones. It is used in various scientific, engineering, and data analysis applications, including:

  1. Data Initialization: Like np.zeros, np.ones is used to initialize arrays before filling them with actual data, simplifying the setup of data structures for computations.
  2. Matrix Operations: In linear algebra and matrix operations, creating arrays filled with ones of specific dimensions is a common practice, especially when defining identity matrices or initializing weights in neural networks.
  3. Image Processing: In image processing, you may need to create masks or arrays with constant values, which can be represented using arrays filled with ones.

Advantages of np.ones:

  1. Efficiency: NumPy arrays are implemented in C and are highly efficient, making np.ones a fast and memory-efficient way to create arrays filled with ones.
  2. Ease of Use: The function is straightforward to use, requiring you to specify the desired shape as an argument.
  3. Compatibility: NumPy arrays created using np.ones can seamlessly integrate with other NumPy functions and libraries for further data manipulation and analysis.

Disadvantages of np.ones:

  1. Fixed Value: np.ones initializes the array with ones, so it may not be suitable if you need to initialize with other values.
  2. Data Type: By default, np.ones creates arrays with floating-point data types. If you need integer values, you’ll need to specify the dtype argument.

Example using np.ones 

Suppose you want to create a NumPy array to represent the daily user sign-ups for “freshers.in” for a week (7 days). You can use np.ones for this task:

import numpy as np
# Views for website : www.freshers.in 
# Create an array representing daily user sign-ups for a week (7 days)
users_per_day = np.ones(7, dtype=int)
# Assign sample data for user sign-ups
users_per_day[0] = 30
users_per_day[1] = 42
users_per_day[2] = 28
users_per_day[3] = 35
users_per_day[4] = 45
users_per_day[5] = 18
users_per_day[6] = 38
print("Daily user sign-ups for freshers.in:")
print(users_per_day)

numpy ones @ Freshers.inWe import NumPy as np.
We use np.ones(7, dtype=int) to create an integer NumPy array with 7 elements initialized to one.
We then assign sample data to represent daily user sign-ups.

Refer more on python here :

Refer more on python NumPy here 

Author: user