1

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?

2
  • 1
    It would be great if you could share an example of your data. This error occurs when you have two columns with same name. Commented Mar 29, 2018 at 12:54
  • 1
    Try passing Categories as a columns parameter as well Commented Mar 29, 2018 at 12:54

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

Needed to use this code instead:

columns = df.Category.values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.