Task03: loc多级索引前应该先排序

multi_index = pd.MultiIndex.from_product([['M','F','Unknown'],[1,2,3]],names=['Sex','Class'])
multi_col = pd.MultiIndex.from_product([['Mid-term','Final'],['CN','UK','JP']],names=['score','Nationality'])
df_multi = pd.DataFrame(np.random.randn(9,6)*5+80,index=multi_index,columns=multi_col).round()
idx = pd.IndexSlice
df_multi.sort_index(inplace=True)
print(df_multi.loc[idx['Unknown':, ('Mid-term', 'UK'):]])


教程里说要先排序我其实是看到了的

但其实这样只做了行索引的排序,其实列索引也需要排序,所以我一开始总是报错
pandas.errors.UnsortedIndexError: 'Key length (2) was greater than MultiIndex lexsort depth (0)'
再做一下列排序:df_multi.sort_index(axis=1,inplace=True)
然后就可以正常输出了!

总结:多级索引排序的时候最好行列都排序一下,防止报错