Home > database >  How to plot value_counts from groupby?
How to plot value_counts from groupby?

Time:07-05

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? Thanks.

CodePudding user response:

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

  • Related