5

I want to count the number of student who got 0-5 grade in one dataset

I use this function final_grade_num =pd.value_counts(final_grade) to get a result like

4.0    487
3.0    432
2.0    376
5.0    334
1.0    232
0.0    139

however, I want to get a sorted list like

0.0 139, 1.0 232...5.0 334

because I need to use this dataset to draw a plot

plt.bar(range(0,6), final_grade_num)

Is there any method to change, I tried to use sorted method, but the result shows it depends on the number of students, not grade

2
  • just chain with sort_values
    – yatu
    Commented Apr 11, 2020 at 15:09
  • final_grade.value_counts().plot(). Commented Apr 11, 2020 at 15:12

1 Answer 1

9

value_counts() has a sort argument that defaults to True. Just set it to False and it will be sorted by value instead.

df['col'].value_counts(sort = False).plot.bar(title='My Title')

Or:

df['col'].value_counts().sort_index().plot.bar()
6
  • thanks but I didn't understand of df['col'] meaning and where do I put 'final_grade_num' as parameter?
    – 4daJKong
    Commented Apr 11, 2020 at 15:22
  • df is the name of your dataframe, and col is the column you want to use. because i don't know the specific names of your dataframe and columns Commented Apr 11, 2020 at 15:23
  • thank you again but how to show the plot, I use "data['grades'].value_counts(sort = False).plot.bar(title='final grade')" but there is no image here, this is my first time to see this method. Is it base on matplotlib or others?
    – 4daJKong
    Commented Apr 11, 2020 at 15:34
  • I think import matplotlib.pyplot as plt and plt.show() would do it. Commented Apr 11, 2020 at 15:53
  • Thanks a lot! but why the x-label is vertical not horizontal? how to change these parameters? I find plot.bar() even don't have 'title' parameter but it can work.
    – 4daJKong
    Commented Apr 11, 2020 at 16:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.