重命名多重索引的单列pandas列

2 投票
1 回答
1085 浏览
提问于 2025-04-18 12:41

我有一个数据框,它有多个索引。列的样子是这样的:

例如,数据框:

      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

1 个回答

2

你可以这样做。

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

我不太明白你为什么要这样使用多重索引的列。希望这对你有帮助。

撰写回答