python - 更改 pandas.MultiIndex 的顺序

标签 python pandas dataframe indexing

我的DataFrame具有以下MultiIndex:

 MultiIndex(levels=[[False, True], [False, True], [False, True], [False, True], [False, True], [False, True], [False, True], [False, True], [False, True]],
               labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1]],
               names=['M016105', 'M743110', 'N237000', 'N239000', 'N241000', 'P010014', 'Z050001', 'Z050002', 'Z050005'])

HTML 渲染如下所示:

enter image description here

标题中的标签列表(names)已自动按字母顺序排序。但是,我想通过传递列表来确定它们的显示顺序。如何做到这一点?

我认为仅仅为 names 分配不同的列表就会破坏数据,因为表值不会自动以不同的方式排序。

最佳答案

使用DataFrame.reorder_levels :

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
}).set_index(['A','B','C','D'])


df = df.reorder_levels(['B','C','A','D']).sort_index()
print (df)
         E  F
B C A D      
4 3 f 0  4  b
  7 a 1  5  a
  9 c 5  6  a
5 2 e 1  2  b
  4 d 7  9  b
  8 b 3  3  a

关于python - 更改 pandas.MultiIndex 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54040923/

相关文章:

python - 查找与另一列 Pandas 中的唯一值关联的列中的值的交集

python - 将字符串二进制转换为单独的位 python dataframe

python - 在 Tensorflow 的 Dataset API 中,如何将一个元素映射为多个元素?

python - 如何找到给定值将被另一个系列达到/交叉的索引?

python - 在哪里放置更新数据库的预定功能,以免干扰?

python-3.x - 根据 Python 中另一个数据帧的列对一个数据帧的行(具有重复项的列)进行排序

python - 在没有 for 循环的情况下在数据框中“过采样”笛卡尔数据?

python - 多索引数据框删除每组最大值的行

python - 将不同维度的数组 append 到单个数组

python - 在Python中读取2字节的I2C事务