增加(创建)
df1=pd.DataFrame(np.arange(12).reshape(4,3),index=[list("AABB"),[1,2,1,2]],columns=[list("XXY"),[10,11,10]]) df1.index=pd.MultiIndex.from_arrays([list("AABB"),[3,4,3,4]],names=["AB","num"])
df = df.set_index(['class','id'])
修改
df1.columns.names=['XY','sum']
df1.index.names=['AB','num']
df1.index=pd.MultiIndex.from_arrays([list("AABB"),[3,4,3,4]],names=["AB","num"])
df1.swaplevel('AB','num')
查询
df.loc[('A',slice(None)),:]
df2.loc[('语文',slice(None)),:]
UnsortedIndexError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)'
对index排序后切片选择index
df2 = df2.sort_index(level='课程')
df2.loc[('语文',slice(None)),:]
获取相应内容
.get_level_values() Index level int/name: 获取对应级别的索引
参考:https://blog.csdn.net/weixin_38168620/article/details/80071141