To repeat elements of an Index, use the index.repeat() method in Pandas. Set the number of repetitions as an argument. At first, import the required libraries −
import pandas as pd
Creating Pandas index −
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')
Display the Pandas index −
print("Pandas Index...\n",index)Repeat elements of the index −
print("\nResult after repeating each index element twice...\n",index.repeat(2))
Example
Following is the code −
import pandas as pd
# Creating Pandas index
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)
# repeat elements of the index
print("\nResult after repeating each index element twice...\n",index.repeat(2))Output
This will produce the following output −
Pandas Index... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport') Number of elements in the index... 6 The dtype object... object Result after repeating each index element twice... Index(['Car', 'Car', 'Bike', 'Bike', 'Airplane', 'Airplane', 'Ship', 'Ship', 'Truck', 'Truck', 'Suburban', 'Suburban'], dtype='object', name='Transport')