在 Pandas 中重新索引 Pivot Table 丢失边距函数?

Re-indexing in Pandas Pivot Table lose margins function?

 ```
    import numpy as np 
    import pandas as pd 
    import matplotlib.pyplot as plt
    import seaborn as sns
    import datetime
        
    
    
    df = pd.read_excel("Baltimore Towing Division.xlsx",sheet_name="TowingData")
    
   
    df['Month'] = pd.DatetimeIndex(df['TowedDate']).strftime("%b")
    df['Week day'] = pd.DatetimeIndex(df['TowedDate']).strftime("%a")
        
   
    monthOrder = ['Jan', 'Feb', 'Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    dayOrder = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
    
       
    Pivotdf = pd.pivot_table(df, values='TowedDate',index='Month',
                            columns='Week day',
                            fill_value=0,
                            aggfunc= 'count', 
                            margins = True, margins_name='Total')
  
    print(Pivotdf)
```

在数据透视表 table 中添加总计行和总计列,但月份和星期日杂乱无章。

如果我为月份和星期几添加任何类型的重新排序功能,由于某种原因,Pivot table 它会丢失边距,但会正确排序月份和星期几。

枢轴代码:

    Pivotdf = pd.pivot_table(df, values='TowedDate',index='Month',
                            columns='Week day',
                            fill_value=0,
                            aggfunc= 'count', 
                            margins = True, margins_name='Total').loc[monthOrder,dayOrder]

您丢失了 Total,因为它不包含在 monthOrderdayOrder 中:

Pivotdf = pd.pivot_table(df, values='TowedDate',index='Month',
                        columns='Week day',
                        fill_value=0,
                        aggfunc= 'count', 
                        margins = True, margins_name='Total') \
            .loc[monthOrder + ['Total'], dayOrder + ['Total']]
print(Pivotdf)

# Output
Week day  Mon  Tue  Wed  Thu  Fri  Sat  Sun  Total
Month                                             
Jan         0    0    1    0    0    0    0      1
Feb         1    1    0    0    1    2    1      6
Mar         0    1    0    0    2    1    1      5
Apr         0    0    1    1    0    0    0      2
May         0    0    1    0    0    1    1      3
Jun         0    1    0    0    0    0    1      2
Jul         0    1    2    1    1    0    1      6
Aug         1    0    1    1    0    0    2      5
Sep         2    0    1    0    1    0    0      4
Oct         2    1    0    0    0    1    0      4
Nov         1    2    0    0    2    1    1      7
Dec         0    1    1    0    2    1    0      5
Total       7    8    8    3    9    7    8     50