Skip to main content

tile

Construct an array by repeating A the number of times given by reps.
numpy.tile(A, reps)
A
array_like
The input array.
reps
array_like
The number of repetitions of A along each axis. If reps has length d, the result will have dimension of max(d, A.ndim).
Returns: ndarray - The tiled output array.

Description

If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If A.ndim > d, reps is promoted to A.ndim by prepending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

Examples

import numpy as np

# Repeat 1-D array
a = np.array([0, 1, 2])
print(np.tile(a, 2))
# array([0, 1, 2, 0, 1, 2])

# Tile in 2D
print(np.tile(a, (2, 2)))
# array([[0, 1, 2, 0, 1, 2],
#        [0, 1, 2, 0, 1, 2]])

# Tile in 3D
print(np.tile(a, (2, 1, 2)))
# array([[[0, 1, 2, 0, 1, 2]],
#        [[0, 1, 2, 0, 1, 2]]])

# Tile 2-D array
b = np.array([[1, 2], [3, 4]])
print(np.tile(b, 2))
# array([[1, 2, 1, 2],
#        [3, 4, 3, 4]])

print(np.tile(b, (2, 1)))
# array([[1, 2],
#        [3, 4],
#        [1, 2],
#        [3, 4]])

# Tile with different repetitions per axis
c = np.array([1, 2, 3, 4])
print(np.tile(c, (4, 1)))
# array([[1, 2, 3, 4],
#        [1, 2, 3, 4],
#        [1, 2, 3, 4],
#        [1, 2, 3, 4]])

See Also

  • repeat - Repeat elements of an array
  • broadcast_to - Broadcast an array to a new shape

repeat

Repeat each element of an array after themselves.
numpy.repeat(a, repeats, axis=None)
a
array_like
Input array.
repeats
int or array of ints
The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.
axis
int
default:"None"
The axis along which to repeat values. By default, use the flattened input array, and return a flat output array.
Returns: ndarray - Output array which has the same shape as a, except along the given axis.

Examples

import numpy as np

# Repeat a scalar
print(np.repeat(3, 4))
# array([3, 3, 3, 3])

# Repeat array elements (no axis specified)
x = np.array([[1,2],[3,4]])
print(np.repeat(x, 2))
# array([1, 1, 2, 2, 3, 3, 4, 4])

# Repeat along axis 1 (columns)
print(np.repeat(x, 3, axis=1))
# array([[1, 1, 1, 2, 2, 2],
#        [3, 3, 3, 4, 4, 4]])

# Different repetitions per element
print(np.repeat(x, [1, 2], axis=0))
# array([[1, 2],
#        [3, 4],
#        [3, 4]])

# 1-D array with varying repeats
a = np.array([1, 2, 3])
print(np.repeat(a, [2, 3, 1]))
# array([1, 1, 2, 2, 2, 3])

See Also

  • tile - Tile an array
  • unique - Find the unique elements of an array

Build docs developers (and LLMs) love