Numpy repeat allows you to repeat elements of any dimensional array. With repeating of elements, it also flattens any multi-dimensional array into a single dimension array. In this entire tutorial, you will know various examples that implement the numpy repeat function.
numpy.repeat(a, repeats, axis=None)
Here is the explanation of the parameter.
a: It is the input array and can be of any dimension, Single or Multi-Dimensional array.
repeats: Int or array of int type.
axis: The axis along which to repeat values. It can be 0 and 1.
Numpy repeat can be used to generate duplicates of a number. For example, I am passing a=3 and repeats = 7. You will get the following output.
np.repeat(a=3,repeats=7)
Output
The method is the same for repeating the 1D Numpy array. Just pass it with the value of the repeat. For example, I want each element of the NumPy array to repeat two times. Then I will use the following code.
Array Creation
array_1d = np.array([1,2,3,4,5,6])
Repetition
np.repeat(array_1d,repeats=2)
Output
In the same way, you can repeat elements any number of times. Try to repeat elements three times using the given code and paste its output in the comment box.
np.repeat(array_1d,repeats=3)
Now let’s repeat a 2D array. Here it has 3 Cases. We will look at each of them. Let’s create a Sample 2D Numpy array.
2D Array Creation
array_2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
If you don’t define the axis parameter in the NumPy repeat method, then the output of it is flattening the NumPy array.
np.repeat(array_2d,repeats=2)
Output
Now if you use the axis parameter then you will get a 2-D array as the output. Pass the axis =0 as an extra argument inside the repeat() method. The elements of the array will be repeated along rows or downward.
np.repeat(array_2d,repeats=2,axis=0)
In this case, if you will use axis =1, then elements will be repeated along with columns or horizontally. Execute the below lines of code.
np.repeat(array_2d,repeats=2,axis=0)
Output
Some readers might relate numpy.repeat() method with numpy.tile() method. As both return copies. But the main difference is that repeat() return copies of each element but tile() repeats the entire array.
Hope this tutorial has helped you in making duplicates of the NumPy array. If you want to more about it or some other queries then please contact us. We are always ready to help you.
Source: