NumPy repeat()

The repeat() method repeats the elements of the input arrays a given number of times.

Example

import numpy as np

numbers = np.array([0, 1, 2, 3])

# repeat each element twice repeatedArray = np.repeat(numbers, 2)
print(repeatedArray) # Output : [0 0 1 1 2 2 3 3]

repeat() Syntax

The syntax of repeat() is:

numpy.repeat(array, repetitions, axis)

repeat() Arguments

The repeat() method takes three arguments:

  • array - an array with elements to be repeated
  • repetitions - number of times the element repeats
  • axis(optional) - axis along which to repeat the elements of the array

repeat() Return Value

The repeat() method returns the array with repeated elements.


Example 1: numpy.repeat()

import numpy as np

# create a 2D array
array1 = np.array([[0, 1], [2, 3]])

# set the number of times each element should repeat
repetitions = 3

# repeat each element thrice repeatedArray = np.repeat(array1, repetitions)
print(repeatedArray)

Output

[0 0 0 1 1 1 2 2 2 3 3 3]

Here, the 2D array array1 is first fattened and each of its elements is repeated thrice.


Example 2: numpy.repeat() With Axis

In case of multi-dimensional arrays, we can use the axis parameter to specify the axis along which the repetition should take place.

When the axis is 0, rows of the array repeat vertically. And, when the axis is 1, columns repeat horizontally.

Let's see an example.

import numpy as np

array1 = np.array([[0, 1], [2, 3]])

repetitions = 2

# repeat the elements along axis 0 repeatedArray = np.repeat(array1, repetitions, 0)
print('Along axis 0\n', repeatedArray)
# repeat the elements along axis 1 repeatedArray = np.repeat(array1, repetitions, 1)
print('Along axis 1\n', repeatedArray)

Output

Along axis 0
[[0 1]
 [0 1]
 [2 3]
 [2 3]]
Along axis 1
 [[0 0 1 1]
 [2 2 3 3]]

Example 3: Uneven Repetition

Examples so far repeat every element of the array a fixed number of times.

However, we can repeat different elements by different amounts.

import numpy as np

array1 = np.array([[0, 1, 2, 3]])

# set different repetition counts for each array element repetitions = [2, 3, 1, 2] # uneven repetition of the elements repeatedArray = np.repeat(array1, repetitions)
print(repeatedArray)

Output

[0 0 1 1 1 2 3 3]

Here, the first element(0) repeats 2 times, the second element(1) repeats 3 times, and so on.


Example 4: Array Creation Using Repeat

We can also create arrays using repeat().

import numpy as np

# create an array of four 3s 
repeatedArray = np.repeat(3, 4)

print(repeatedArray)

Output

[3 3 3 3]