Python | Pandas Index.repeat()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas Index.repeat() function repeat elements of an Index. The function returns a new index where each element of the current index is repeated consecutively a given number of times.

Syntax: Index.repeat(repeats, *args, **kwargs)

Parameters :
repeats : The number of repetitions for each element.
**kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy.

Returns : Newly created Index with repeated elements.



Example #1: Use Index.repeat()() function to repeat the elements of the index 2 times.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd
import pandas as pd
  
# Creating the index
idx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug',
                        'Mastiff', None, 'Beagle'])
  
# Print the Index
idx

chevron_right


Output :

Let’s repeat the index elements 2 times.

filter_none

edit
close

play_arrow

link
brightness_4
code

# to repeat the values
idx.repeat(2)

chevron_right


Output :

As we can see in the output, the function has returned a new index with all the values repeated 2 times. One important thing to notice is that the function has also repeated the NaN value.

Example #2: Use Index.repeat() function to repeat the value of index 3 times.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd
import pandas as pd
  
# Creating the index
idx = pd.Index([22, 14, 8, 56, None, 21, None, 23])
  
# Print the Index
idx

chevron_right


Output :

Let’s repeat the index elements 3 times.

filter_none

edit
close

play_arrow

link
brightness_4
code

# to repeat the values
idx.repeat(3)

chevron_right


Output :

As we can see in the output, the function has returned a new index with all the values repeated 3 times. One important thing to notice is that the function has also repeated the NaN value.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.