Python Pandas - Repeat elements of an Index

To repeat elements of an Index, use the index.repeat() method in Pandas. This method creates a new Index where each element is repeated a specified number of times.

Creating a Basic Index

First, let's create a simple Pandas Index ?

import pandas as pd

# Creating Pandas index
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], name='Transport')

# Display the Pandas index
print("Original Index:")
print(index)
Original Index:
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport')

Using repeat() Method

The repeat() method repeats each element the specified number of times ?

import pandas as pd

index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], name='Transport')

# Repeat each element twice
repeated_index = index.repeat(2)
print("After repeating each element twice:")
print(repeated_index)
After repeating each element twice:
Index(['Car', 'Car', 'Bike', 'Bike', 'Airplane', 'Airplane', 'Ship', 'Ship',
       'Truck', 'Truck', 'Suburban', 'Suburban'], dtype='object', name='Transport')

Different Repetition Patterns

You can specify different repetition counts for each element using an array ?

import pandas as pd

index = pd.Index(['A', 'B', 'C'], name='Letters')

# Different repetitions: A repeated 3 times, B repeated 1 time, C repeated 2 times
custom_repeat = index.repeat([3, 1, 2])
print("Custom repetition pattern:")
print(custom_repeat)
Custom repetition pattern:
Index(['A', 'A', 'A', 'B', 'C', 'C'], dtype='object', name='Letters')

Working with Numeric Index

The repeat() method works with numeric indices as well ?

import pandas as pd

numeric_index = pd.Index([10, 20, 30], name='Numbers')

# Repeat each number 3 times
repeated_numeric = numeric_index.repeat(3)
print("Repeated numeric index:")
print(repeated_numeric)
print(f"Size: {repeated_numeric.size}")
Repeated numeric index:
Index([10, 10, 10, 20, 20, 20, 30, 30, 30], dtype='int64', name='Numbers')
Size: 9

Conclusion

The repeat() method is useful for duplicating index elements when you need to expand your data structure. It preserves the original index name and dtype while creating a new Index with repeated elements.

Updated on: 2026-03-26T16:04:34+05:30

557 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements