
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Repeat Elements of an Index in Python Pandas
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')
Advertisements