- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Create Multiindex from dataframe
To create Multiindex from DataFrame, use the MultiIndex. from_frame() method. At first, let us create a Dictionary of lists −
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22'] }
Next, create a Pandas DataFrame from the above dictionary of lists −
dataFrame = pd.DataFrame(d)
Now create multiindex using from_frame() −
print(pd.MultiIndex.from_frame(dataFrame))
Example
Following is the code −
import pandas as pd # dictionary of lists d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22']} # creating dataframe from the above dictionary of lists dataFrame = pd.DataFrame(d) print("DataFrame...\n",dataFrame) # creating multiple indexes print(pd.MultiIndex.from_frame(dataFrame))
Output
This will produce the following output −
DataFrame... Car Date_of_purchase 0 BMW 2020-10-10 1 Lexus 2020-10-12 2 Audi 2020-10-17 3 Mercedes 2020-10-16 4 Jaguar 2020-10-19 5 Bentley 2020-10-22 MultiIndex ([( 'BMW','2020-10-10'), ( 'Lexus','2020-10-12'), ( 'Audi','2020-10-17'), ('Mercedes','2020-10-16'), ( 'Jaguar','2020-10-19'), ( 'Bentley '2020-10-22')], names=['Car,Date _of_purchase'])
Advertisements
To Continue Learning Please Login
Login with Google