Python——从 Pandas 数据框的多层列索引中移除一层


要从多层列索引中移除一层,请使用 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'])]

# forming multiindex dataframe
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")])

# multiindex array
arr = [np.array(['car', 'car', 'car','bike','bike', 'bike', 'truck', 'truck', 'truck']),

np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])]

# forming multiindex dataframe
dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr,columns=items)

# labelling index
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

更新于: 2021-09-13

3K+ 查看

开启您的 职业生涯

完成课程并获得认证

开始
广告