我有一个带有多索引的数据框。这些列看起来像:
例如。 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。
关于python - 重命名多索引pandas列的单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24661323/