0
0
NumPydata~5 mins

np.ones() for one-filled arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.ones() to quickly create arrays filled with the number one. This helps when you need a starting point or a simple array full of ones for calculations.

When you want to create a mask or filter array filled with ones.
When initializing weights or biases in machine learning models with ones.
When you need a simple array of ones to add or multiply with other arrays.
When testing functions that require input arrays filled with ones.
When you want to create a placeholder array with all elements set to one.
Syntax
NumPy
import numpy as np

array = np.ones(shape, dtype=None, order='C')

shape can be an integer or a tuple of integers defining the array size.

dtype sets the data type of the array elements (default is float).

Examples
This creates a simple 1D array with 5 elements, all set to 1.0.
NumPy
import numpy as np

# Create a 1D array of length 5 filled with ones
array_1d = np.ones(5)
print(array_1d)
This creates a 2D array with 3 rows and 4 columns, all elements are 1.0.
NumPy
import numpy as np

# Create a 2D array (3 rows, 4 columns) filled with ones
array_2d = np.ones((3, 4))
print(array_2d)
This creates an empty array because the size is zero.
NumPy
import numpy as np

# Create an empty array with zero size
empty_array = np.ones(0)
print(empty_array)
This creates a 1D array of integers instead of floats.
NumPy
import numpy as np

# Create a 1D array of integers filled with ones
int_array = np.ones(4, dtype=int)
print(int_array)
Sample Program

This program shows an initial array of zeros, then creates a new array of the same length filled with ones using np.ones(). It prints both arrays to compare.

NumPy
import numpy as np

# Create a 1D array of length 6 filled with ones
array_before = np.array([0, 0, 0, 0, 0, 0])
print('Before creating ones array:')
print(array_before)

# Use np.ones to create a new array filled with ones
array_ones = np.ones(6)
print('\nAfter creating ones array:')
print(array_ones)
OutputSuccess
Important Notes

Time complexity: Creating an array with np.ones() is very fast and runs in O(n) where n is the number of elements.

Space complexity: The array uses memory proportional to the number of elements.

A common mistake is to forget that the default data type is float, so the ones are 1.0, not integer 1, unless you specify dtype=int.

Use np.ones() when you need an array filled with ones quickly. For zeros, use np.zeros(). For other values, use np.full().

Summary

np.ones() creates arrays filled with the number one.

You can specify the shape and data type of the array.

This function is useful for initializing arrays or masks in data science tasks.