Kodeclik Blog
Python numpy.repeat()
numpy.repeat() is a very handy function in the Python numpy library that can be used to repeat elements in an array. In this blog post, we will discuss how to use numpy.repeat() and its different parameters.
The numpy.repeat() function takes two mandatory arguments: the array to be repeated and the number of repetitions. It returns a new array with the repeated elements.
Here is an example code snippet:
import numpy as np
# Create a numpy array
arr = np.array([1, 2, 3, 2, 1])
# Repeat each element two times
new_arr = np.repeat(arr, 2)
# Print the new array
print(new_arr)
The output is:
[1 1 2 2 3 3 2 2 1 1]
Let us try it with a two-dimensional array:
import numpy as np
# Create a numpy array
arr = np.array([[1, 2], [3, 4]])
# Repeat each element two times
new_arr = np.repeat(arr, 2)
# Print the new array
print(new_arr)
The output is:
[1 1 2 2 3 3 4 4]
Note what has happened: numpy.repeat() flattens the array into a one-dimensional array before repetition. This is the default behavior. If you do not wish this to happen, you must specify the axis parameter, which specifies the axis along which to repeat the array.
Here is an example program to accomplish this:
import numpy as np
# Create a numpy array
arr = np.array([[1, 2], [3, 4]])
# Repeat each element two times
new_arr = np.repeat(arr, 2, axis=0)
# Print the new array
print(new_arr)
In this case, we specify axis=0 which does the repetition across rows. In other words, the number of rows is doubled but the number of columns stays the same. The output is:
[[1 2]
[1 2]
[3 4]
[3 4]]
If on the other hand we try:
import numpy as np
# Create a numpy array
arr = np.array([[1, 2], [3, 4]])
# Repeat each element two times
new_arr = np.repeat(arr, 2, axis=1)
# Print the new array
print(new_arr)
we will get:
[[1 1 2 2]
[3 3 4 4]]
To summarize, numpy.repeat() takes two compulsory arguments, viz. the array to be repeated and the number of times to be repeated. It uses an optional argument specifying the axis along which the repetition is to be performed.
If you liked learning about numpy.repeat(), learn about Python’s numpy.cumsum() function!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.