
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
Create MultiIndex from Arrays in Python Pandas
We will see how to create multiindex from arrays using the MultiIndex.from_arrays(). At first, let us create an array of cars −
car = ['Audi', 'Lexus', 'Tesla', 'Mercedes', 'BMW', 'Toyota', 'Nissan', 'Bentley', 'Mustang']
Create another array for our example, that would include the Registration Price −
reg_price = [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
Now, we will use the MultiIndex.from_arrays(). Also set the names for the levels in the index.
Example
Following is the code −
import pandas as pd # array of cars car = ['Audi', 'Lexus', 'Tesla', 'Mercedes', 'BMW', 'Toyota', 'Nissan', 'Bentley', 'Mustang'] # array of registration price reg_price = [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] # Combining arrays and creating multi-index print(pd.MultiIndex.from_arrays([car, reg_price], names=('car', 'reg_price')))
Output
This will produce the following output −
MultiIndex(levels=[[u'Audi', u'BMW', u'Bentley', u'Lexus', u'Mercedes', u'Mustang', u'Nissan', u'Tesla', u'Toyota'], [900, 1000, 1100, 1150, 1300, 1350, 1400, 1700, 1800]], labels=[[0, 3, 7, 4, 1, 8, 6, 2, 5], [1, 6, 2, 0, 7, 8, 4, 3, 5]], names=[u'car', u'reg_price'])
Advertisements