Numpy tile() Function



The Numpy tile() function is used to construct a new array by repeating an input array a specified number of times. This function is particularly useful for creating patterned or repeated arrays in various shapes. It works with both one-dimensional and multi-dimensional arrays.

In Numpy tile() function, if the number of repetitions (reps) has a length l, the resulting array will have dimensions equal to max(l, Array.ndim), ensuring compatibility between the input array's dimensions and the specified repetition pattern.

Syntax

Following is the syntax of the Numpy tile() function −

numpy.tile(A, reps)

Parameters

Following are the parameters of the Numpy tile() function −

  • A: The input array that will be repeated.
  • reps: Specifies the number of repetitions along each axis. It can be an integer or a sequence of integers (e.g., a tuple).
  • If an integer, the input array is repeated that number of times along all dimensions.
  • If a sequence, it specifies the number of repetitions along each axis.

Return Type

This function returns a new array containing the repeated copies of the input array.

Example

Following is a basic example to repeat a 1-dimensional array using the Numpy tile() function −

import numpy as np
my_array = np.array([1, 2, 3])
tiled_array = np.tile(my_array, 2)
print("Original Array:", my_array)
print("Tiled Array:", tiled_array)

Output

Following is the output of the above code −

Original Array: [1 2 3]
Tiled Array: [1 2 3 1 2 3]

Example: Repeating Along Multiple Dimensions

We can use the reps parameter to specify the number of repetitions along each dimension.

In the following example we have demonstrated tiling of a 2-dimensional array using numpy.tile() function −

import numpy as np
my_array = np.array([[1, 2], [3, 4]])
tiled_array = np.tile(my_array, (2, 3))
print("Original Array:\n", my_array)
print("Tiled Array:\n", tiled_array)

Output

Following is the output of the above code −

Original Array:
 [[1 2]
  [3 4]]
Tiled Array:
 [[1 2 1 2 1 2]
  [3 4 3 4 3 4]
  [1 2 1 2 1 2]
  [3 4 3 4 3 4]]

Example: Using Scalar as Input

The numpy.tile() function can also repeat scalar values by treating them as 0-dimensional arrays.

In the following example, the value 5 is repeated to create an array with the shape (3, 2)

import numpy as np
scalar = 5
tiled_scalar = np.tile(scalar, (3, 2))
print("Scalar Value:", scalar)
print("Tiled Array:\n", tiled_scalar)

Output

Following is the output of the above code −

Scalar Value: 5
Tiled Array:
 [[5 5]
  [5 5]
  [5 5]]
numpy_array_manipulation.htm
Advertisements