Skip to content
Advertisement

count multiple value in dataframe

I have a dataframe that shows answers of a multiple choice question of 5 students:

id     Question 1
0          a;b;c
1          a;c
2          b
3          a;d
4          b;c;d

And I want to count how many times does a choice been selected. For example, the final answer should be

a:3
b:3
c:3
d:2

So is there a quick way to get the solution using python?

Besides, I am using the data from the dataframe for visualization in Tableau. Tableau counts like this:

a;b;c appear once
a;c   appear once
b     appear once
a;d   appear once
b;c;d appear once

So is there a way to get the above result directly using Tableau? Or I have to do something in python then using tableau.

Thanks

Advertisement

Answer

You can try below code to count the occurrence of each choice in a pandas dataframe column:

data = pd.DataFrame({'id':[0, 1,2,3,4], 'Question1':['a;b;c','a;c','b','a;d','b;c;d']})
count = data.Question1.str.split(';', expand=True).stack().value_counts()

output:

a    3
b    3
c    3
d    2
dtype: int64
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement