Python Pandas - 以多索引形式显示数据框的索引
如需以多索引形式显示数据框的索引,请使用 dataframe.index()。首先,让我们创建一个列表词典 -
# 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'] }
根据上述列表词典创建一个数据框 -
dataFrame = pd.DataFrame(d)
现在设置索引列“Car”,然后显示索引 -
dataFrame.set_index(["Car"], inplace=True, append=True, drop=False) print"\nMultiindex...\n",dataFrame.index
示例
代码如下 -
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
输出
此代码会产生以下输出 -
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'])
广告