
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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'])
- Related Articles
- Python - Drop specific rows from multiindex Pandas Dataframe
- Python Pandas - Create Multiindex from arrays
- Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
- Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns
- Python Pandas - Create a DataFrame from DateTimeIndex ignoring the index
- Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns but avoid setting the index of the returned DataFrame
- Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns and substitute index level names
- Create a Pipeline and remove a column from DataFrame - Python Pandas
- Python Pandas - Getting values from a specific level in Multiindex
- Python – Strip whitespace from a Pandas DataFrame
- Create a Pandas Dataframe from a dict of equal length lists in Python
- Python Pandas - Create a DataFrame from the TimeDeltaIndex object ignoring the original index
- Python Pandas - Create a DataFrame from original index but enforce a new index
- Python Pandas - How to Sort MultiIndex
- Python Pandas - Rearrange levels in MultiIndex

Advertisements