2016-09-25 44 views
0

我有一个这样的熊猫数据帧,我想用pd.pivot_table尝试使用熊猫枢像Excel数据透视

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中制作)转动:

enter image description here

我尝试这样做:

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

我弗洛翼错误。

AssertionError: Grouper and axis must be same length 

在此先感谢您。

回答

2

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 

但这哈克变种作品:

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 
+0

谢谢你的回答!我用你的解决方案。 – Hangon