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:
The output is:
Let us try it with a two-dimensional array:
The output is:
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:
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:
If on the other hand we try:
we will get:
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.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.