Python Pandas - 以多索引的形式显示数据帧的索引
要以多索引的形式显示数据帧的索引,请使用.首先,让我们创建一个列表字典-dataframe.index()
#列表字典 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'] }
从上面的列表字典创建一个DataFrame-
dataFrame = pd.DataFrame(d)
现在,设置索引列“Car”并显示索引-
dataFrame.set_index(["Car"], inplace=True, append=True, drop=False) print"\nMultiindex...\n",dataFrame.index
示例
以下是代码-
import pandas as pd #列表字典 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'] } #creatingdataframefromtheabovedictionaryoflists dataFrame = pd.DataFrame(d) print"DataFrame...\n",dataFrame #setindexcolumn dataFrame.set_index(["Car"], inplace=True, append=True, drop=False) print"\nMultiindex...\n",dataFrame.index输出结果
这将产生以下输出-
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'])