py4u blog

Mastering numpy.ones_like() in Python: A Comprehensive Guide

NumPy, the fundamental package for scientific computing in Python, provides a suite of functions to create and manipulate arrays efficiently. Among these, numpy.ones_like() stands out as a versatile tool for generating arrays filled with the value 1 that mirror the shape and data type of an existing array. Whether you’re working on data preprocessing, numerical simulations, or machine learning, ones_like() simplifies the process of initializing arrays with consistent dimensions—saving time and reducing errors.

This blog will dive deep into numpy.ones_like(), covering its syntax, parameters, practical examples, best practices, and comparisons with similar functions. By the end, you’ll be equipped to use ones_like() effectively in your projects.

2026-10

Table of Contents#

  1. What is numpy.ones_like()?
  2. Syntax and Parameters
  3. Return Value
  4. Example Usage
  5. Common Practices
  6. Best Practices
  7. When to Use numpy.ones_like()
  8. Comparison with Similar Functions
  9. Conclusion
  10. References

What is numpy.ones_like()?#

numpy.ones_like(a) is a NumPy function that creates a new array filled with the value 1, where the shape (dimensions) and data type (dtype) of the new array are identical to those of the input array a.

This is particularly useful when you need an array with the same structure as an existing array but populated with 1s. Instead of manually extracting the shape of a and passing it to numpy.ones(), ones_like() streamlines the process with a single function call.

Syntax and Parameters#

The full syntax of numpy.ones_like() is:

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

Parameters:#

  • a (array_like): The input array whose shape and dtype will be mirrored. This can be a NumPy array, list, tuple, or any object that can be converted to a NumPy array.
  • dtype (data type, optional): The data type of the output array. If None (default), the dtype of a is used.
  • order ({'C', 'F', 'A', 'K'}, optional): Specifies the memory layout of the output array:
    • 'C': Row-major (C-style) order.
    • 'F': Column-major (Fortran-style) order.
    • 'A': Preserve input order if a is Fortran-contiguous, otherwise use 'C'.
    • 'K' (default): Match the layout of a as closely as possible.
  • subok (bool, optional): If True (default), the output will be a subclass of ndarray if a is a subclass (e.g., numpy.matrix). If False, the output is always a base ndarray.
  • shape (int or sequence of ints, optional): Override the shape of the output array. If provided, the output will have this shape instead of a’s shape.

Return Value#

numpy.ones_like() returns a NumPy array (or subclass, if subok=True) filled with 1s, with:

  • Shape: Same as a (unless shape is specified).
  • Dtype: Same as a (unless dtype is specified).

Example Usage#

Let’s explore practical examples to understand how ones_like() works.

Basic Example: Matching Shape and Dtype#

Suppose you have an array a and want a new array of 1s with the same shape and dtype:

import numpy as np
 
# Create an input array
a = np.array([[1, 2, 3], [4, 5, 6]])  # Shape: (2, 3), dtype: int64 (default)
 
# Generate ones_like array
b = np.ones_like(a)
 
print("Input array (a):")
print(a)
print("\nOutput array (b):")
print(b)
print("\nShape of b:", b.shape)  # (2, 3)
print("Dtype of b:", b.dtype)    # int64

Output:

Input array (a):
[[1 2 3]
 [4 5 6]]

Output array (b):
[[1 1 1]
 [1 1 1]]

Shape of b: (2, 3)
Dtype of b: int64

Here, b has the same shape (2, 3) and dtype int64 as a, filled with 1s.

Specifying a Custom Dtype#

By default, ones_like() inherits the dtype of a. To override this, specify the dtype parameter:

a = np.array([1.5, 2.0, 3.7])  # dtype: float64
 
# Create ones_like array with dtype=int32
b = np.ones_like(a, dtype=np.int32)
 
print("Input array (a) dtype:", a.dtype)  # float64
print("Output array (b):", b)             # [1 1 1]
print("Output array (b) dtype:", b.dtype)  # int32

Output:

Input array (a) dtype: float64
Output array (b): [1 1 1]
Output array (b) dtype: int32

Here, b uses int32 instead of a’s float64.

Handling Different Array Types (Lists, Matrices)#

ones_like() works with non-ndarray inputs (e.g., lists) by first converting them to NumPy arrays. It also handles subclasses like numpy.matrix:

# Example 1: Input is a list
list_a = [10, 20, 30]
b = np.ones_like(list_a)
print("List input -> array output:", b)  # [1 1 1] (shape (3,), dtype int64)
 
# Example 2: Input is a numpy.matrix
matrix_a = np.matrix([[1, 2], [3, 4]])  # Subclass of ndarray
c = np.ones_like(matrix_a)
print("\nMatrix input -> matrix output:\n", c)  # Matrix([[1, 1], [1, 1]])
print("Type of c:", type(c))  # numpy.matrix (since subok=True)

Output:

List input -> array output: [1 1 1]

Matrix input -> matrix output:
 [[1 1]
 [1 1]]
Type of c: <class 'numpy.matrix'>

To force a base ndarray instead of a subclass, set subok=False:

d = np.ones_like(matrix_a, subok=False)
print("Type of d (subok=False):", type(d))  # numpy.ndarray

Output:

Type of d (subok=False): <class 'numpy.ndarray'>

Overriding Shape with the shape Parameter#

The shape parameter lets you override the output shape, ignoring a’s shape:

a = np.array([1, 2, 3])  # Shape: (3,)
 
# Override shape to (2, 2)
b = np.ones_like(a, shape=(2, 2))
 
print("Input shape:", a.shape)  # (3,)
print("Output shape:", b.shape)  # (2, 2)
print("Output array:\n", b)

Output:

Input shape: (3,)
Output shape: (2, 2)
Output array:
 [[1 1]
 [1 1]]

Use this when you need 1s but with a different shape than a.

Edge Cases: Empty Arrays and Scalars#

ones_like() handles edge cases like empty arrays and scalars gracefully:

# Empty array input
empty_a = np.array([])
empty_b = np.ones_like(empty_a)
print("Empty array output:", empty_b)  # [] (shape (0,), dtype float64)
 
# Scalar input
scalar_a = np.array(5)  # Shape: ()
scalar_b = np.ones_like(scalar_a)
print("Scalar output:", scalar_b)  # 1 (shape (), dtype int64)

Output:

Empty array output: []
Scalar output: 1

Common Practices#

  • Maintaining Shape Consistency: Use ones_like() to ensure new arrays align with existing data structures (e.g., in machine learning, initializing masks or weight arrays with the same shape as input data).
  • Quick Prototyping: When testing code, ones_like() provides a fast way to generate placeholder arrays with the correct dimensions.
  • Avoiding Hardcoded Shapes: Instead of manually writing np.ones((2, 3)), use ones_like(existing_array) to future-proof code if existing_array’s shape changes.

Best Practices#

  1. Explicitly Specify dtype When Needed: Avoid unexpected behavior by specifying dtype if the output needs a different type than a. For example:

    a = np.array([1, 2, 3], dtype=np.uint8)  # 8-bit unsigned int
    # Use float32 for numerical stability in computations
    b = np.ones_like(a, dtype=np.float32)
  2. Use subok=False for Base Arrays: If you need a standard ndarray (not a subclass like matrix), set subok=False to avoid compatibility issues.

  3. Mind Memory Layout with order: For large arrays, specify order='C' or order='F' to optimize memory access (e.g., order='C' for row-major operations in Python).

  4. Avoid Overusing shape Parameter: The shape parameter is useful but can make code less readable. Prefer np.ones(shape) if you don’t need to mirror a’s dtype.

When to Use numpy.ones_like()#

  • When you need 1s with the same shape/dtype as an existing array: e.g., creating a mask for element-wise operations.
  • In numerical simulations: Initializing arrays for intermediate results that match the input data’s structure.
  • In data preprocessing: Generating dummy arrays for padding or alignment with existing datasets.

Comparison with Similar Functions#

FunctionPurposeKey Difference
numpy.ones_like(a)Array of 1s with shape/dtype of aFills with 1s
numpy.zeros_like(a)Array of 0s with shape/dtype of aFills with 0s
numpy.empty_like(a)Uninitialized array with shape/dtype of aFaster but contains garbage values (use when overwriting all elements)
numpy.full_like(a, val)Array filled with val (any value)General-purpose; fills with a custom value

Example Comparison:

a = np.array([[1, 2], [3, 4]])
 
print("ones_like:", np.ones_like(a))
print("zeros_like:", np.zeros_like(a))
print("empty_like:", np.empty_like(a))  # Values are uninitialized (may vary)
print("full_like (val=5):", np.full_like(a, 5))

Output:

ones_like: [[1 1]
 [1 1]]
zeros_like: [[0 0]
 [0 0]]
empty_like: [[         0 1072693248]  # Garbage values
 [1073741824 1074266112]]
full_like (val=5): [[5 5]
 [5 5]]

Conclusion#

numpy.ones_like() is a powerful tool for creating arrays of 1s with the same shape and dtype as an existing array. It simplifies array initialization, reduces boilerplate, and ensures consistency in your code. By mastering its parameters (e.g., dtype, order, subok) and best practices, you can leverage ones_like() to write cleaner, more efficient NumPy code.

References#