尝试像 excel 枢轴那样使用 pandas 枢轴

Trying to use pandas pivot like excel pivot

我有一个像这样的 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