pandas中Groupby使用(五)-根据索引级别分组

#-*- coding:utf-8 -*-
import pandas as pd
import numpy as np
columns=pd.MultiIndex.from_arrays([['US','US','US','JP','JP'],[1,3,5,1,3]],names=['city','tenor'])
hier_df=pd.DataFrame(np.random.randn(4,5),columns=columns)
print hier_df
print hier_df.groupby(level='city',axis=1).count()
# city         US                            JP          
# tenor         1         3         5         1         3
# 0     -0.442238 -0.798524  0.701981 -0.354014  0.612403
# 1      1.934450  0.968853  1.115006  2.794805 -0.518528
# 2      0.628730  1.521953 -1.051380  0.874810 -1.361220
# 3      1.844472  1.428690 -0.593901 -0.557560  0.557546
# city  JP  US
# 0      2   3
# 1      2   3
# 2      2   3
# 3      2   3

猜你喜欢

转载自blog.csdn.net/qq_36076233/article/details/77850482
今日推荐