.repeat()
The .repeat()
function in NumPy is used to duplicate items in an array. It provides the option to specify the number of times each element appears, and whether that repetition happens across a specific axis or not. If no axis is mentioned, the array is flattened before repeating.
Syntax
numpy.repeat(a, repeats, axis=None)
Parameters:
a
: The array to work with. This is where the elements come from.repeats
: Anint
or array ofints
. If anint
, each element ofa
is repeated that many times. If an array, it must match the length ofa
(ifaxis=None
) or the length ofa
along the specified axis.axis
(Optional): Sets the direction for repeating.
Return value:
Returns a NumPy array with repeated elements. The shape of the result depends on the shape of a
, the repeats
value, and whether an axis
is specified.
Example 1: Repeating Elements Without Specifying the axis
Parameter
Here’s a simple example where each value in a one-dimensional array gets repeated twice:
import numpy as np# Create an arrayarr = np.array([1, 2, 3])# Repeat each element in the array 2 timesprint(np.repeat(arr, 2))
The above code produces the following output:
[1 1 2 2 3 3]
Example 2: Directional Repetition Using the axis
Parameter
For multi-dimensional arrays, using the axis
parameter controls which direction the repetition flows:
import numpy as nparr2d = np.array([[1, 2], [3, 4]])# Repeat each element in the array 2 times along axis 0print(np.repeat(arr2d, 2, axis=0))# Repeat each element in the array 2 times along axis 1print(np.repeat(arr2d, 2, axis=1))
The above code produces the following output:
[[1 2][1 2][3 4][3 4]][[1 1 2 2][3 3 4 4]]
Codebyte Example: Repeating Each Element Three Times
This codebyte example repeats every item in an array three times in a row:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours