```
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)
```
在資料透視表中添加總計行和總計列,但月份和星期天數雜亂無章。

如果我為月份和作業日添加任何型別的重新排序功能,由于某種原因,資料透視表會丟失邊距,但會執行正確的月份和作業日順序。

樞軸代碼:
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]
uj5u.com熱心網友回復:
你輸了Total,因為它不包含在monthOrderand中dayOrder:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447232.html
上一篇:Pandas系列中的扁平化串列
下一篇:如何在屬性中獲取控制器端點資訊?
