Python - 从 Pandas 数据框中的多级列索引中删除一个级别
要从多级列索引中删除一个级别,请使用.我们已经使用isused来按列创建索引。columns.droplevel()Multiindex.from_tuples()
首先,按列创建索引-
items = pd.MultiIndex.from_tuples([("Col 1", "Col 1", "Col 1"),("Col 2", "Col 2", "Col 2"),("Col 3", "Col 3", "Col 3")])
接下来,创建一个多索引数组并形成一个多索引数据帧
arr = [np.array(['car', 'car', 'car','bike','bike', 'bike', 'truck', 'truck', 'truck']), np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])] #形成多索引数据帧 dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr,columns=items)
标记索引-
dataFrame.index.names = ['level 0', 'level 1']
在索引0处下降一个级别-
dataFrame.columns = dataFrame.columns.droplevel(0)
示例
以下是代码
import numpy as np import pandas as pd items = pd.MultiIndex.from_tuples([("Col 1", "Col 1", "Col 1"),("Col 2", "Col 2", "Col 2"),("Col 3", "Col 3", "Col 3")]) #multiindexarray arr = [np.array(['car', 'car', 'car','bike','bike', 'bike', 'truck', 'truck', 'truck']), np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])] #形成多索引数据帧 dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr,columns=items) #labellingindex dataFrame.index.names = ['level 0', 'level 1'] print"DataFrame...\n",dataFrame print"\nDropping a level...\n"; dataFrame.columns = dataFrame.columns.droplevel(0) print"Updated DataFrame..\n",dataFrame输出结果
这将产生以下输出
DataFrame... Col 1 Col 2 Col 3 Col 1 Col 2 Col 3 Col 1 Col 2 Col 3 level 0 level 1 car valueA 1.691127 0.315145 -0.695925 valueB -2.077182 -2.027643 -0.523965 valueC 1.021402 -0.384421 0.640215 bike valueA -2.271217 0.197185 0.304847 valueB 0.119615 -0.520491 -0.746547 valueC 1.856888 -0.491540 -1.754604 truck valueA 0.829854 -0.204102 -1.130511 valueB 0.310692 0.119087 -0.244919 valueC -0.245934 -2.141639 -1.298278 Dropping a level... Updated DataFrame.. Col 1 Col 2 Col 3 Col 1 Col 2 Col 3 level 0 level 1 car valueA 1.691127 0.315145 -0.695925 valueB -2.077182 -2.027643 -0.523965 valueC 1.021402 -0.384421 0.640215 bike valueA -2.271217 0.197185 0.304847 valueB 0.119615 -0.520491 -0.746547 valueC 1.856888 -0.491540 -1.754604 truck valueA 0.829854 -0.204102 -1.130511 valueB 0.310692 0.119087 -0.244919 valueC -0.245934 -2.141639 -1.298278