import numpy as np import pandas as pd #1.风格1 df=pd.DataFrame(np.random.rand(4,2), columns=["A","B"], index=[["1","1","2","2"], ["a","b","a","b"]]) print(df) #2.风格2 mindex=pd.MultiIndex.from_arrays([["a","a","b","b"],[1,2,1,2]])#双层索引对象 df2=pd.DataFrame(np.random.rand(4,2), columns=(["A","B"]), index=mindex) print(df2) #3.风格3 mindex=pd.MultiIndex.from_tuples([("a",1),("a",2),("b",1),("b",2)])#根据元组构建 df3=pd.DataFrame(np.random.rand(4,2), columns=(["A","B"]), index=mindex) print(df3) #4.风格4 mindex=pd.MultiIndex.from_product([["a","b"],[1,2]])#根据元组构建 df4=pd.DataFrame(np.random.rand(4,2), columns=(["A","B"]), index=mindex) print(df4) #5.风格5 mindex=pd.MultiIndex(levels=[["a","b"],[1,2]], codes=[[0,0,1,1],[0,1,0,1]])#a对应00,b对应11 df4=pd.DataFrame(np.random.rand(4,2), columns=(["A","B"]), index=mindex) print(df4) #6. index=[("beijing",2007),("beijing", 2017), ("beijing", 2027),("shenzhen",2007), ("shenzhen",2017),("shenzhen",2027)] money=np.random.rand(6) Mindex=pd.MultiIndex.from_tuples(index) city=pd.DataFrame(money,index=Mindex) print(city)