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

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.