我有一个看起来像这样的DataFrame:
>>> df = pd.DataFrame(index=pd.MultiIndex.from_tuples([(num,letter,color) for num in range(1,3) for letter in ['a','b','c'] for color in ['Red','Green']], names=['Number','Letter','Color'])) >>> df['Value'] = np.random.randint(1,100,len(df)) >>> df Value Number Letter Color 1 a Red 97 Green 61 b Red 97 Green 98 c Red 91 Green 47 2 a Red 17 Green 63 b Red 26 Green 73 c Red 34 Green 68
但我实际上希望我的索引被命令'Letter,Color,Number'.
我目前这样做如下:
>>> df.reset_index().set_index(['Letter','Color','Number']) Value Letter Color Number a Red 1 97 Green 1 61 b Red 1 97 Green 1 98 c Red 1 91 Green 1 47 a Red 2 17 Green 2 63 b Red 2 26 Green 2 73 c Red 2 34 Green 2 68
这是最好的方法吗?
最好用来reorder_levels
操纵MultiIndex级别的顺序.只需按照您想要的顺序传递级别名称/数字列表:
>>> df.reorder_levels(['Letter','Color','Number']) Value Letter Color Number a Red 1 41 Green 1 56 b Red 1 43 Green 1 42 c Red 1 89 Green 1 18 a Red 2 55 Green 2 93 b Red 2 64 Green 2 9 c Red 2 21 Green 2 93
还有swaplevel
,如果你只是想交换两个级别的位置.