 # Numpy Repeat Example : How to use it ( 1D and 2D Array)

### GET FREE AMZAON AUDIOBOOKS      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.

## Syntax of The Numpy repeat method

``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.

## Examples of Numpy Repeat Function

### Example 1: How to repeat a Single Number

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

### Example 2: Repeat a Single Dimensional Numpy Array

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)``

### Example 2: Repeat Two Dimensional Numpy Array

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]])``

#### Case 1: Flatten with Simple Repetition of 2D Array

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

#### Case 2: Repetition of 2D Array with axis =0, (TOWARDS ROW)

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)``

#### Case 3: Repetition of 2D Array with axis =1, (TOWARDS COLUMN)

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

## Conclusion

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.

Source:

Numpy Offical Documentation 