Mysterious
Mysterious

Reputation: 881

Pandas pivot table error

Following code gives

Code:

table_channel = pd.pivot_table(data=df,values = 'Category',index = 
['ID'], aggfunc='count')

Output:

ID    Category
1     2
2     11
3     5
4     3

Right now it's giving total count of different categories of Category column. Need output like:

ID    Category1    Category2  Category3
1         0            1          1
2         5            4          2 and so on

I used this code to rectify but it did not work:

table_channel = pd.pivot_table(df,values = 'Category',columns = 'Category',index = ['ID'], aggfunc='count')

Error is that grouper for Category not 1 dimensional. What is wrong?

Upvotes: 1

Views: 1152

Answers (2)

Mysterious
Mysterious

Reputation: 881

Needed to use this code instead:

columns = df.Category.values

Upvotes: 1

BENY
BENY

Reputation: 323306

You can using crosstab

pd.crosstab(df.ID,df.Category).add_prefix('Category')
Out[1335]: 
Category  Category2  Category3  Category5  Category11
ID                                                   
1                 1          0          0           0
2                 0          0          0           1
3                 0          0          1           0
4                 0          1          0           0

Upvotes: 3

Related Questions