py4u blog

Mastering numpy.full_like(): A Complete Guide to Array Initialization

In the world of numerical computing with Python, NumPy stands as a cornerstone library that provides powerful array operations. Among its many utility functions, numpy.full_like() offers a convenient way to create arrays filled with a specific value while maintaining the shape and data type of an existing array. This function is particularly useful when you need to initialize arrays with predefined values while preserving the structural characteristics of a reference array.

Whether you're working on machine learning pipelines, scientific computations, or data analysis tasks, understanding full_like() can significantly streamline your array initialization workflows. This comprehensive guide will explore every aspect of this function, from basic usage to advanced applications.

2026-10

Table of Contents#

  1. Introduction
  2. Understanding the Basics
  3. Syntax and Parameters
  4. Practical Examples
  5. Common Use Cases
  6. Best Practices and Performance
  7. Comparison with Alternatives
  8. Conclusion
  9. References

Understanding the Basics#

What is numpy.full_like()?#

numpy.full_like() is a NumPy function that creates a new array with the same shape and data type as a given array, but filled with a specified constant value. It combines the functionality of numpy.shape() and numpy.dtype extraction with array initialization.

Key Characteristics:#

  • Shape Preservation: The output array maintains the exact dimensions of the input array
  • Data Type Consistency: By default, uses the same data type as the reference array
  • Memory Efficiency: Creates optimized arrays without unnecessary copying
  • Flexible Initialization: Allows overriding of data type and memory layout

Syntax and Parameters#

The complete syntax for numpy.full_like() is:

numpy.full_like(a, fill_value, dtype=None, order='K', subok=True)

Parameter Breakdown:#

ParameterTypeDescriptionDefault
aarray_likeReference array whose shape and dtype are usedRequired
fill_valuescalarValue to fill the new array withRequired
dtypedata-typeOverride the data type of the resultNone
order{'C', 'F', 'A', 'K'}Memory layout of the array'K'
subokboolWhether to return subclass of a if possibleTrue

Understanding the order Parameter:#

  • 'C': C-style row-major memory layout
  • 'F': Fortran-style column-major memory layout
  • 'A': 'F' if a is Fortran contiguous, 'C' otherwise
  • 'K': Match the layout of a as closely as possible

Practical Examples#

Basic Usage Examples#

import numpy as np
 
# Example 1: Basic usage with integer array
original_array = np.array([[1, 2, 3], [4, 5, 6]])
filled_array = np.full_like(original_array, 7)
print("Original array:")
print(original_array)
print("\nFilled array:")
print(filled_array)
# Output:
# [[7 7 7]
#  [7 7 7]]
 
# Example 2: Using with float array
float_array = np.array([1.5, 2.5, 3.5])
filled_float = np.full_like(float_array, 10.0)
print(filled_float)
# Output: [10. 10. 10.]
 
# Example 3: Boolean array
bool_array = np.array([True, False, True])
filled_bool = np.full_like(bool_array, False)
print(filled_bool)
# Output: [False False False]

Advanced Examples with Parameters#

import numpy as np
 
# Example 4: Overriding data type
original = np.array([1, 2, 3], dtype=np.int32)
filled_float = np.full_like(original, 5.7, dtype=np.float64)
print(f"Original dtype: {original.dtype}")
print(f"Filled dtype: {filled_float.dtype}")
print(filled_float)
# Output:
# Original dtype: int32
# Filled dtype: float64
# [5.7 5.7 5.7]
 
# Example 5: Memory layout control
# Create a 2D array with specific layout
arr_2d = np.array([[1, 2, 3], [4, 5, 6]], order='F')  # Fortran contiguous
 
# Preserve memory layout
filled_c = np.full_like(arr_2d, 0, order='C')
filled_f = np.full_like(arr_2d, 0, order='F')
 
print(f"Original is F-contiguous: {arr_2d.flags['F_CONTIGUOUS']}")
print(f"'C' order is F-contiguous: {filled_c.flags['F_CONTIGUOUS']}")
print(f"'F' order is F-contiguous: {filled_f.flags['F_CONTIGUOUS']}")
 
# Example 6: Working with subclasses
class CustomArray(np.ndarray):
    pass
 
custom_arr = np.array([1, 2, 3]).view(CustomArray)
filled_subok = np.full_like(custom_arr, 9, subok=True)
filled_no_subok = np.full_like(custom_arr, 9, subok=False)
 
print(f"With subok=True: {type(filled_subok)}")
print(f"With subok=False: {type(filled_no_subok)}")

Multi-dimensional Array Examples#

import numpy as np
 
# Example 7: 3D arrays
arr_3d = np.random.rand(2, 3, 4)
filled_3d = np.full_like(arr_3d, 0.5)
 
print(f"Original shape: {arr_3d.shape}")
print(f"Filled shape: {filled_3d.shape}")
print(f"Filled array:\n{filled_3d}")
 
# Example 8: Special values
# Creating arrays with special values
original = np.array([1, 2, 3])
 
# Infinity
inf_array = np.full_like(original, np.inf)
print(f"Infinity array: {inf_array}")
 
# NaN
nan_array = np.full_like(original, np.nan, dtype=np.float64)
print(f"NaN array: {nan_array}")
 
# Complex numbers
complex_array = np.full_like(original, 3+4j, dtype=np.complex128)
print(f"Complex array: {complex_array}")

Common Use Cases#

1. Mask Initialization#

# Creating boolean masks with the same shape as data
data = np.random.rand(100, 50)
mask = np.full_like(data, False, dtype=bool)
# Set specific condition
mask[data > 0.5] = True

2. Accumulator Arrays#

# Initialize accumulator with zeros matching input shape
input_data = np.array([[1, 2], [3, 4]], dtype=np.float32)
accumulator = np.full_like(input_data, 0.0)
 
# Accumulate values
for i in range(5):
    accumulator += input_data * i

3. Template-based Array Creation#

# Create arrays based on template structure
template = np.ones((3, 3), dtype=np.int16)
identity_like = np.full_like(template, 0)
np.fill_diagonal(identity_like, 1)  # Create identity matrix with same properties

4. Batch Processing#

# Initialize result arrays for batch operations
batch_data = np.random.rand(10, 28, 28)  # 10 images of 28x28
results = np.full_like(batch_data, 0.0)
 
# Process each item
for i in range(batch_data.shape[0]):
    results[i] = batch_data[i] * 2  # Example operation

Best Practices and Performance#

1. Memory Efficiency#

# Good: Uses existing array's memory layout
original = np.array([[1, 2], [3, 4]], order='F')
optimized = np.full_like(original, 0, order='K')  # Matches original layout
 
# Avoid: Manual creation that might not preserve layout
less_optimal = np.full(original.shape, 0, dtype=original.dtype)

2. Data Type Considerations#

# Explicit dtype specification for clarity
original = np.array([1, 2, 3], dtype=np.float32)
 
# Good: Explicit dtype
result = np.full_like(original, 5.0, dtype=np.float64)
 
# Better: Let numpy infer when appropriate
result_auto = np.full_like(original, 5.0)  # Keeps float32

3. Performance Comparison#

import numpy as np
import time
 
def benchmark_methods():
    large_array = np.random.rand(1000, 1000)
    
    # Method 1: full_like
    start = time.time()
    result1 = np.full_like(large_array, 7.5)
    time1 = time.time() - start
    
    # Method 2: ones_like * value
    start = time.time()
    result2 = np.ones_like(large_array) * 7.5
    time2 = time.time() - start
    
    # Method 3: zeros_like + value
    start = time.time()
    result3 = np.zeros_like(large_array) + 7.5
    time3 = time.time() - start
    
    print(f"full_like: {time1:.6f}s")
    print(f"ones_like * value: {time2:.6f}s")
    print(f"zeros_like + value: {time3:.6f}s")
 
benchmark_methods()

Comparison with Alternatives#

numpy.full_like() vs numpy.full()#

import numpy as np
 
template = np.array([[1, 2], [3, 4]])
 
# Using full_like (preserves dtype and layout)
result_like = np.full_like(template, 5)
 
# Using full (requires manual specification)
result_full = np.full(template.shape, 5, dtype=template.dtype)
 
print("Equivalent results:", np.array_equal(result_like, result_full))

numpy.full_like() vs Manual Initialization#

# Method 1: full_like (recommended)
arr1 = np.full_like(template, 0)
 
# Method 2: Manual with zeros (less flexible)
arr2 = np.zeros_like(template)
 
# Method 3: Multiplication approach
arr3 = np.ones_like(template) * 0
 
# full_like is most explicit about intent and most flexible

When to Use Each Method:#

  • Use full_like() when you have a template array and want to maintain its properties
  • Use full() when you know the shape and dtype explicitly
  • Use zeros_like()/ones_like() when filling with 0 or 1 specifically

Conclusion#

numpy.full_like() is a powerful and efficient function that simplifies array initialization while preserving the important characteristics of reference arrays. Its ability to maintain shape, data type, and memory layout makes it invaluable for:

  1. Code Readability: Clearly expresses intent to create filled arrays based on templates
  2. Maintainability: Reduces errors by automatically preserving array properties
  3. Performance: Optimized implementation with minimal overhead
  4. Flexibility: Customizable through dtype and order parameters

By mastering full_like() and understanding when to use it versus alternatives, you can write more efficient, readable, and maintainable NumPy code. This function is particularly valuable in scenarios where array properties need to be conserved across multiple operations, such as in machine learning pipelines, image processing, and scientific computing applications.

References#

  1. NumPy Documentation: numpy.full_like()
  2. NumPy Array Creation Routines: Array Creation
  3. Python NumPy Tutorial: DataCamp NumPy Tutorial
  4. NumPy Performance Guidelines: NumPy Performance Python

Additional Resources#