2016-09-25 29 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