How to groupby and count binomial variable in python? and make a plot of this

Viewed 130

i have a dataframe like this:

country question1 question2
france yes no
italy yes yes
france yes no
germany no yes
italy no yes

i would like to get an output like a pivot table or a group with a count of yes/no for each Question and each country(similar countifs of excel).

I tried many methods as df.groupby(country).value_counts() or df.groupby(country).sum("Yes")

but i cannot get the result wanted.

And i would like to make a chart of this result obtained, only for the YES answer.

Someone can give me an advice?

Thanks

1 Answers

How to groupby and count binomial variables?

We can encode the values in the columns question1 and question2 using get_dummies then sum the encoded values per unique country to get the counts of number of Yes and No for each question per country

counts = pd.get_dummies(df.set_index('country')).sum(level=0)

         question1_no  question1_yes  question2_no  question2_yes
country                                                          
france              0              2             2              0
italy               1              1             0              2
germany             1              0             0              1

How to make a plot of this?

Filter the question columns containing _Yes suffixed in their names, then call the plot method of pandas dataframe with kind=bar to create a bar chart showing the counts of questions having Yes corresponding to each country

counts.filter(like='_yes').plot(kind='bar') 

enter image description here

Related