【问题标题】:Pandas : How to plot bar graph for each month over countsPandas:如何绘制每个月的条形图
【发布时间】:2021-07-07 07:25:40
【问题描述】:

我有一个数据框df 如下:

Student_id   Date_of_exam(d/m/y)  Student_Performance
1            1/4/2020              Excellent
1            30/12/2019            Poor
1            26/12/2019            Medium
2            3/1/2021              Medium
2            10/1/2021             Poor
3            4/5/2020              Poor
3            22/8/2020             Excellent

我如何获得以 x-axis 为月-年的条形图(例如:y-ticks:2019 年 12 月、2020 年 1 月、2020 年 2 月)和 y-axis - 学生总数(计数) Student_Performance == Poor.

请提供任何想法,在此先感谢。

【问题讨论】:

  • 你能告诉我们你已经尝试过什么吗?
  • 我是 python 新手,不知道如何继续,这是我提到的但没有正确df['Date_of_exam'] = pd.to_datetime(df['Date_of_exam']) s = df.resample('M', on='Date_of_exam')[['Student_Performance'== 'Poor']].size()

标签: python python-3.x pandas dataframe matplotlib


【解决方案1】:

希望下面的 sn-p 是您正在寻找的:

import seaborn as sns
import pandas as pd

df = pd.read_csv("student_data.csv") #assuming the data is in the csv file

# get only month and year from datetime column (date of exam)
df['date_col'] = df['Date_of_exam(d/m/y)'].dt.to_period('M') 

# group by based on month and year after filtering poor graded students
data = df[df['Student_Performance']=='Poor'].groupby(['date_col']).size().reset_index(name
    = 'count')  

ax = sns.barplot(x="date_col", y="count", data=data) #plot using seaborn

输出:

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 2022-12-11
    • 2017-08-27
    • 1970-01-01
    • 2015-06-12
    • 2016-05-24
    • 2019-04-12
    相关资源
    最近更新 更多