import numpy as np import pandas as pd 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[0])#代表全部数据 print(city.loc["beijing"])#取出行beijing print(city.iloc[0])#取出第一行 idx=pd.IndexSlice#处理索引 print(city.loc[idx["beijing"],idx[:]])#取出北京 print(city.loc[idx["beijing",2007],idx[:]])#取出北京2007 print(city.loc[idx[:,2027],idx[:]])#取出所有2027 print(city.unstack(level=0))#生成表格 print(city.unstack(level=1))#生成表格 print(city.mean(level=0))#城市算平均值 print(city.mean(level=1))#年度算平均值,聚合操作 print(city.sum(level=0))#根据城市求和 print(city.sum(level=1))#根据年度求和 print(city.max(level=0)) print(city.min(level=1))