如何在不对索引进行排序的情况下执行groupy.apply()?

时间:2017-10-20 10:00:52

标签: python pandas pandas-groupby

我有以下数据:

myData = pd.DataFrame({'K':[810,820,825,830,840,855,842,823],'Type':
['C','C','P','P','C','B','A','B'],'S':[978,978,978,978,978,966,925,923],'R':
[0.05,0.05,0.05,0.05,0.05,0.03,0.04,0.05]})


    K   R   S   Type
0   810 0.05    978 C
1   820 0.05    978 C
2   825 0.05    978 P
3   830 0.05    978 P
4   840 0.05    978 C
5   855 0.03    966 B
6   842 0.04    925 A
7   823 0.05    923 B

我使用groupby来获取此信息:

      K    R    S   Type
Type                    
A   6   842 0.04    925 A
B   7   823 0.05    923 B
C   0   810 0.05    978 C
P   2   825 0.05    978 P

但我想要的是Type顺序不会改变。

  K    R    S   Type
Type                    

C   0   810 0.05    978 C
P   2   825 0.05    978 P
B   7   823 0.05    923 B
A   6   842 0.04    925 A

1 个答案:

答案 0 :(得分:2)

使用groupby时使用sort = False,例如

myData.groupby('Type',sort=False).mean()
            K     R      S
Type                         
C     823.333333  0.05  978.0
P     827.500000  0.05  978.0
B     839.000000  0.04  944.5
A     842.000000  0.04  925.0