To display the index of dataframe in the form of multiindex, use the dataframe.index(). At first, let us create a dictionary of lists −
# 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'] }
Create a DataFrame from the above dictionary of lists −
dataFrame = pd.DataFrame(d)
Now, set index column “Car” and display the index −
dataFrame.set_index(["Car"], inplace=True, append=True, drop=False) print"\nMultiindex...\n",dataFrame.index
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 # set index column dataFrame.set_index(["Car"], inplace=True, append=True, drop=False) print"\nMultiindex...\n",dataFrame.index
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... MultiIndex(levels=[[0, 1, 2, 3, 4, 5], [u'Audi', u'BMW', u'Bentley', u'Jaguar', u'Lexus', u'Mercedes']], labels=[[0, 1, 2, 3, 4, 5], [1, 4, 0, 5, 3, 2]], names=[None, u'Car'])