简体   繁体   English

我需要帮助从 dataframe 绘制条形图

[英]I need help plotting a bar graph from a dataframe

I have the following dataframe:我有以下 dataframe:

    AQI         Year     City
0   349.407407  2015    'Patna'
1   297.024658  2015    'Delhi'
2   283.007605  2015    'Ahmedabad'
3   297.619178  2016    'Delhi'
4   282.717949  2016    'Ahmedabad'
5   250.528701  2016    'Patna'
6   379.753623  2017    'Ahmedabad'
7   325.652778  2017    'Patna'
8   281.401216  2017    'Gurugram'
9   443.053221  2018    'Ahmedabad'
10  248.367123  2018    'Delhi'
11  233.772603  2018    'Lucknow'
12  412.781250  2019    'Ahmedabad'
13  230.720548  2019    'Delhi'
14  217.626741  2019    'Patna'
15  214.681818  2020    'Ahmedabad'
16  181.672131  2020    'Delhi'
17  162.251366  2020    'Patna'

I would like to group data for each year, ie 2015, 2016, 2017 2018...2020 on the x axis, with AQI on the y axis.我想对每年的数据进行分组,即 2015 年、2016 年、2017 年 2018...2020 年在 x 轴上,AQI 在 y 轴上。 I am a newbie and please excuse the lack of depth in my question.我是新手,请原谅我的问题缺乏深度。

You can "pivot" your data to support your desired plotting output.您可以“旋转”您的数据以支持您想要的绘图 output。 Here we set the rows as Year , columns as City , and values as AQI .在这里,我们将行设置为Year ,将列设置为City ,将值设置为AQI

pivot = pd.pivot_table(
    data=df,
    index='Year',
    columns='City',
    values='AQI',
)
Year Ahmedabad艾哈迈达巴德 Delhi德里 Gurugram古尔格拉姆 Lucknow勒克瑙 Patna巴特那
2015 2015 283.007605 283.007605 297.024658 297.024658 NaN NaN 349.407407 349.407407
2016 2016 年 282.717949 282.717949 297.619178 297.619178 NaN NaN 250.528701 250.528701
2017 2017 379.753623 379.753623 NaN 281.401216 281.401216 NaN 325.652778 325.652778
2018 2018 443.053221 443.053221 248.367123 248.367123 NaN 233.772603 233.772603 NaN
2019 2019 412.781250 412.781250 230.720548 230.720548 NaN NaN 217.626741 217.626741
2020 2020 214.681818 214.681818 181.672131 181.672131 NaN NaN 162.251366 162.251366

Then you can plot this pivot table directly:然后可以直接用plot这个pivot表:

pivot.plot.bar(xlabel='Year', ylabel='AQI')

在此处输入图像描述


Old answer旧答案

Are you looking for the mean AQI per year?您在寻找每年的平均AQI 吗? If so, you can do some pandas chaining, assuming your data is in a DataFrame df :如果是这样,您可以做一些 pandas 链接,假设您的数据在 DataFrame df中:

df.groupby('Year').mean().plot.bar(xlabel='Year', ylabel='AQI')

aqi_groupby_year

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM