多级 pandas 数据框中的自定义排序列 [英] Custom sorting columns in multi level pandas dataframe

查看:60
本文介绍了多级 pandas 数据框中的自定义排序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大数据框,其中包含2个级别的列,但有1个级别的行,并且我尝试按以下方式对其进行排序: 0级:按字母顺序; 级别1:自定义排序.

I have a big data frame with 2 levels columns, but 1 level rows, and I am trying to sort it as follows: level 0: alphabetically; level 1: custom sort.

import pandas as pd
dictionary = {'A' : {'M': [1,2,3,4,5],
                     'L': [6,7,8,9,1],
                     'F': [3,5,1,3,5]  },
              'C' : {'M': [2,3,4,5,6],
                     'L': [7,8,9,1,2],
                     'F': [0,1,6,3,5]  },
              'B' : {'M': [1,5,2,5,3],
                     'L': [9,5,6,3,4],
                     'F': [6,2,7,1,5] }
         }
reform = {(outerKey, innerKey): values for outerKey, innerDict in dictionary.iteritems() for innerKey, values in innerDict.iteritems()}
pd.DataFrame(reform,index=['g','h','i','j','k'])

那我要拥有的是

#        A          B           C
#        F  L   M   F   L   M   F   L   M
#    g  3   6   1   6   9   1   0   7   2
#    h  5   7   2   2   5   5   1   8   3
#    i  1   8   3   7   6   2   6   9   4
#    j  3   9   4   1   3   5   3   1   5
#    k  5   1   5   5   4   3   5   2   6

问题

如何将列的顺序指定为0级的A,B,C和1级的F,M,L?

Question

How can I specify the order of columns to be A, B, C on level 0 and F, M, L on level 1?

### OUT
#        A          B           C
#        F  M   L   F   M   L   F   M   L

我尝试使用pd.IndexSlice.loc,但是我仍然只获得字母顺序.

I was trying with pd.IndexSlice and .loc, but I still get only alphabetic order.

推荐答案

您可以使用

You can achieve this using reindex_axis, this accepts a labels arg, axis and level:

In [20]:
df = df.reindex_axis(list('FML'), axis=1, level=1)
df

Out[20]:
   A        B        C      
   F  M  L  F  M  L  F  M  L
g  3  1  6  6  1  9  0  2  7
h  5  2  7  2  5  5  1  3  8
i  1  3  8  7  2  6  6  4  9
j  3  4  9  1  5  3  3  5  1
k  5  5  1  5  3  4  5  6  2

由于@Nickli Maveli,您还可以使用 reindex 实现相同的目的:

Thanks to @Nickli Maveli you can also use reindex to achieve the same:

In [22]:
df = df.reindex(columns=list('FML'), level=1)
df

Out[22]:
   A        B        C      
   F  M  L  F  M  L  F  M  L
g  3  1  6  6  1  9  0  2  7
h  5  2  7  2  5  5  1  3  8
i  1  3  8  7  2  6  6  4  9
j  3  4  9  1  5  3  3  5  1
k  5  5  1  5  3  4  5  6  2

这篇关于多级 pandas 数据框中的自定义排序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆