熊猫Pivot_Table保留顺序

拉胡尔·兰詹(Rahul Ranjan)
>>> df
   A   B   C      D
0  foo one small  1
1  foo one large  2
2  foo one large  2
3  foo two small  3
4  foo two small  3
5  bar one large  4
6  bar one small  5
7  bar two small  6
8  bar two large  7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
          small  large
foo  one  1      4
     two  6      NaN
bar  one  5      4
     two  6      7

我希望输出如上所示,但是得到排序的输出。bar位于foo之上,依此类推。

学生

创建时pivot_table,索引会自动按字母顺序排序。不仅foobar,您还可能会注意到smalllarge已排序。如果您想排foo在最前面,则可能需要sort再次使用它们sortlevel如果您期望此处的示例所示为输出,则进行排序,A并且C可能两者都需要。

table.sortlevel(["A","B"], ascending= [False,True], sort_remaining=False, inplace=True)
table.sortlevel(["C"], axis=1, ascending=False,  sort_remaining=False, inplace=True)
print(table)

输出:

C        small  large
A   B                
foo one  1.0    4.0  
    two  6.0    NaN   
bar one  5.0    4.0  
    two  6.0    7.0  

更新:

删除索引名称AB以及C

table.columns.name = None
table.index.names = (None, None)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章