熊猫如何将数据表按升序和降序同时摆放?

时间:2018-10-26 18:24:06

标签: python pandas sorting dataframe pivot-table

df=pd.DataFrame({'Country':["AU","GB","KR","US","GB","US","KR","AU","US"],'Region Manager':['TL','JS','HN','AL','JS','AL','HN','TL','AL'],'Campaign Stage':['Start','Develop','Develop','Launch','Launch','Start','Start','Launch','Develop'],'Curr_Sales': [453,562,236,636,893,542,125,561,371],'Curr_Revenue':[4530,7668,5975,3568,2349,6776,3046,1111,4852],'Prior_Sales': [235,789,132,220,569,521,131,777,898],'Prior_Revenue':[1530,2668,3975,5668,6349,7776,8046,2111,9852]})
pd.pivot_table(df, values=['Curr_Sales', 'Curr_Revenue','Prior_Sales','Prior_Revenue'],index=['Country', 'Region Manager','Campaign Stage'],aggfunc=np.sum,margins=True)

enter image description here 我有上面的df和输出的数据透视表。我想先按“广告系列阶段”的升序(开始-开发-启动),然后再按Curr_sales降序对数据透视表进行排序。

我还要如何为每个国家/地区添加小计?

1 个答案:

答案 0 :(得分:1)

您可以在两列中同时使用sort_values

piv_df = pd.pivot_table(df, values=['Curr_Sales', 'Curr_Revenue','Prior_Sales','Prior_Revenue'],
                     index=['Country', 'Region Manager','Campaign Stage'],
                     aggfunc=np.sum,margins=True)


piv_df.sort_values(['Campaign Stage', 'Curr_Sales'], ascending=[True, False])

piv_df
                                       Curr_Revenue  Curr_Sales  \
Country Region Manager Campaign Stage                             
All                                           39875        4379   
GB      JS             Develop                 7668         562   
US      AL             Develop                 4852         371   
KR      HN             Develop                 5975         236   
GB      JS             Launch                  2349         893   
US      AL             Launch                  3568         636   
AU      TL             Launch                  1111         561   
US      AL             Start                   6776         542   
AU      TL             Start                   4530         453   
KR      HN             Start                   3046         125  

您可以在此帖子pandas subtotals on groupby

中看到小计的解决方案