用途:
active_def = pd.pivot_table(data, index = 'InMonth', columns= 'OutMonth', aggfunc= 'count', margins=True)['ID']
OR
您可以使用此一班輪:
數據建立
df = pd.DataFrame(data=np.triu(np.random.randint(0,13,(12,12))),
columns=np.arange(1,13),
index=np.arange(1,13))
計算的行,列和整個數據幀總計:
df.append(pd.Series(df.sum(),name='Total'))\
.assign(Total=df.sum(1))\
.set_value('Total','Total',df.values.sum())
輸出:
1 2 3 4 5 6 7 8 9 10 11 12 Total
1 4 3 6 12 5 9 0 12 1 10 8 10 80.0
2 0 9 8 1 5 1 5 10 7 1 9 2 58.0
3 0 0 2 11 4 0 2 5 4 12 1 7 48.0
4 0 0 0 11 9 2 10 3 0 5 2 10 52.0
5 0 0 0 0 7 12 10 11 12 5 6 0 63.0
6 0 0 0 0 0 12 1 4 1 2 11 0 31.0
7 0 0 0 0 0 0 8 12 8 7 2 1 38.0
8 0 0 0 0 0 0 0 12 7 0 5 9 33.0
9 0 0 0 0 0 0 0 0 12 4 10 9 35.0
10 0 0 0 0 0 0 0 0 0 3 7 1 11.0
11 0 0 0 0 0 0 0 0 0 0 8 2 10.0
12 0 0 0 0 0 0 0 0 0 0 0 5 5.0
Total 4 12 16 35 30 36 36 69 52 49 69 56 464.0
考慮pivot_table的[利潤率](https://pandas.pydata.org/大熊貓-文檔/穩定/ reshaping.html#添加-邊距)。 – Parfait