@@ -129,6 +129,29 @@ pd.pivot_table(df, index=['A', 'B'], columns=['C'], values=['D','E'], aggfunc={'
129
129
pd.pivot_table(df, index = [' A' , ' B' ], columns = [' C' ], values = [' D' ,' E' ], aggfunc = {' D' :len ,' E' :[np.sum, np.mean]})
130
130
131
131
pd.pivot_table(df, index = pd.Grouper(freq = ' M' , key = ' F' ), columns = ' C' , values = ' D' , aggfunc = np.sum) # 类似 resample
132
+
133
+ # 数据透视表复杂操作
134
+ pv_x = pd.pivot_table(df, index = [' 商户' ,' 状态' ],
135
+ values = [' 金额' ],
136
+ columns = [' 月份' ],
137
+ aggfunc = [np.sum, len ],
138
+ fill_value = 0 , margins = True )
139
+ pv_x.columns = pv_x.columns.droplevel(level = [1 ])
140
+ pv_x = pv_x.rename(columns = {' sum' :' 金额' ,' len' :' 件数' }, level = 0 )
141
+ pv_x = pv_x.T.sort_index(level = [1 ,0 ],ascending = [1 ,0 ]).T # 按列名排序
142
+ pv_x.rename({' All' :' 合计' }, axis = 1 , inplace = True )
143
+ pv_x.rename({' All' :' 合计' }, level = 0 , inplace = True )
144
+ pv_x.rename({' ' :' 合计' }, level = 1 , inplace = True )
145
+ pv_x.reindex(index = [(' 商户A' ,' 状态1' ),
146
+ (' 商户A' ,' 状态2' ),
147
+ (' 商户A' ,' 状态3' ),
148
+ (' 商户B' ,' 状态1' ),
149
+ (' 商户B' ,' 状态2' ),
150
+ (' 商户B' ,' 状态3' )]).fillna(0 ) # 手动指定多层级排序
151
+ pv_x1 = pv_x.iloc[:- 1 ,].reindex(index = [' 状态3' ,' 状态2' ,' 状态1' ,' 合计' ],level = 1 ) # 按行排序
152
+ pv_x2 = pv_x.iloc[- 1 :,]
153
+ pv_x = pd.concat([pv_x1, pv_x2], axis = 0 )
154
+ pv_x = pv_x.swaplevel(axis = 1 )
132
155
```
133
156
134
157
<br />
0 commit comments