The repeat() method repeats the elements of the input arrays a given number of times.
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 repeatedrepetitions- number of times the element repeatsaxis(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()
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.
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.
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().
Output
[3 3 3 3]