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

2024-10-05 14:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

示例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

要创建的代码:

^{pr2}$

列名:

[('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

Tags: textdateindexcoljuncol2col3col1
1条回答
网友
1楼 · 发布于 2024-10-05 14:28:17

你能做到的。在

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

我不知道为什么要用这种方式使用多索引列。好吧。在

相关问题 更多 >