How to plot value_counts from groupby

Question:

I have a dataframe with multiple observations in each year.

df = pd.DataFrame({"year": [2000,2000,2000,2001,2001,2001], "A": [1,1,0,0,1,0], "B": [4,4,6,10,10,10]})


    year    A   B
0   2000    1   4
1   2000    1   4
2   2000    0   6
3   2001    0   10
4   2001    1   10
5   2001    0   10

I group it by year and examine value_counts for column A.

df.groupby("year").A.value_counts()

year  A
2000  1    2
      0    1
2001  0    2
      1    1

How do I get a barchart showing the number of times A=1 in each year?

Asked By: Smithey

||

Answers:

Try unstack index A into columns and then plot:

df.groupby("year").A.value_counts().unstack(level=1).plot(kind='bar')

enter image description here

Answered By: Psidom
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.