尝试使用像pandas轴心pandas枢轴

我有一个像这样的pandas数据框架,我想使用pd.pivot_table来枢轴转动

import pandas df = pd.DataFrame({"Id":[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10], "Error":[0, 99, 0, 0, 0, 98, 0, 0, 0, 0, 33, 0, 23, 0, 0, 0, 83, 0]}) 

我试图像这样旋转(在Excel中进行数据透视):

在这里输入图像说明

我试过这个:

 dfPivot = pd.pivot_table(df, index = "Id", columns = df.Error.unique(), values = "Error", aggfunc="count") 

我有以下错误。

 AssertionError: Grouper and axis must be same length 

先谢谢你。

IIUC你可以这样做:

 In [7]: df.pivot_table(index='Id', columns='Error', aggfunc='size', fill_value=0) Out[7]: Error 0 23 33 83 98 99 Id 1 1 0 0 0 0 1 2 2 0 0 0 0 0 3 1 0 0 0 1 0 4 2 0 0 0 0 0 5 2 0 0 0 0 0 6 1 0 1 0 0 0 7 1 1 0 0 0 0 8 2 0 0 0 0 0 9 0 0 0 1 0 0 10 1 0 0 0 0 0 In [8]: df.pivot_table(index='Id', columns='Error', aggfunc='size', fill_value='') Out[8]: Error 0 23 33 83 98 99 Id 1 1 1 2 2 3 1 1 4 2 5 2 6 1 1 7 1 1 8 2 9 1 10 1 

如果你想拥有Grand Total ,你可以使用margins=True参数,但是会有点棘手:

 In [42]: df.pivot_table(index='Id', columns='Error', aggfunc='size', fill_value=0, margins=True) ...skipped... TypeError: 'str' object is not callable 

但这个hacky变体的作品:

 In [43]: (df.assign(x=0) ....: .pivot_table(index='Id', columns='Error', aggfunc='count', ....: fill_value=0, margins=True, margins_name='Grand Total') ....: .astype(int) ....: ) Out[43]: x Error 0 23 33 83 98 99 Grand Total Id 1 1 0 0 0 0 1 2 2 2 0 0 0 0 0 2 3 1 0 0 0 1 0 2 4 2 0 0 0 0 0 2 5 2 0 0 0 0 0 2 6 1 0 1 0 0 0 2 7 1 1 0 0 0 0 2 8 2 0 0 0 0 0 2 9 0 0 0 1 0 0 1 10 1 0 0 0 0 0 1 Grand Total 13 1 1 1 1 1 18 
Interesting Posts