Skip to main content
 首页 » 编程设计

python之重命名多索引 Pandas 列的单列

2024年10月25日10zhoujg

我有一个带有多索引的数据框。这些列看起来像:

例。 DF:

      index date        Text        Text        Text        Text        Text 
OtherText               OtherText1  OtherText1  OtherText1  OtherText1  OtherText1 
Col                     Col1        Col2        Col3        Col4        Col5 
        0   17-Jun-14   1           2           3           4           5 

创建代码:

arrays = [['Date', 'Text', 'Text', 'Text', 'Text', 'Text'], 
      ['', 'OtherText1', 'OtherText1', 'OtherText1', 'OtherText1', 'OtherText1'], 
      ['', 'Col1', 'Col2', 'Col3', 'Col4', 'Col5']] 
df = pd.DataFrame(randn(1,6), columns=arrays) 

列名:

[('date', '', ''), 
 ('text', 'somemoretext', 'Col1'), 
 ('text', 'somemoretext', 'Col2'), 
 ('text', 'somemoretext', 'Col3')...] 

我正在寻找重命名或交换第一列的级别。这没有产生错误,但也没有更改列。

df.rename(columns={"('date', '', '')" : "('', '' 'date')"}, inplace=True) 

如何重新排序和/或重命名多索引中的特定列?

期望的输出:

      index             Text        Text        Text        Text        Text 
OtherText               OtherText1  OtherText1  OtherText1  OtherText1  OtherText1 
Col          date       Col1        Col2        Col3        Col4        Col5 
        0   17-Jun-14   1           2           3           4           5 

请您参考如下方法:

你可以做到这一点。

In [17]: df.set_index('Date').reset_index(col_level=2) 
Out[17]:  
                   Text                                         
             OtherText1                                         
       Date        Col1      Col2      Col3      Col4      Col5 
0 -1.468055   -1.528279 -1.230268  0.010953 -1.344443  0.650798 

我不确定您为什么要以这种方式使用多索引列。 HTH.