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

标签 python pandas dataframe

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

例如。 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/

相关文章:

python - 反转字符串中的单词 - 相同顺序 - 包括空格

python - 在类内打开文件

python - pandas 按 Q1 和 Q3 聚合进行分组

python - 如何从 Pandas 数据框中提取索引?

python - 有条件地填充 Pandas 数据框中的空白值

python - pandas DataFrame to_html 中的粗体列

python - 从 pd 数据帧获取联合概率

python - 比较 DataFrame 中的值并用给定列表中最接近的值替换

Python 在所有可能的变量组合中创建新的列/属性

Python/Pandas 从 csv 创建 zip 文件