0

I have the following 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, i.e. 2015, 2016, 2017 2018...2020 on the x axis, with AQI on the y axis. I am a newbie and please excuse the lack of depth in my question.

Braiam
  • 1
  • 11
  • 47
  • 78
NCoder
  • 13
  • 1
  • Does this answer your question? [Bar graph from dataframe groupby](https://stackoverflow.com/questions/40313727/bar-graph-from-dataframe-groupby) – Glazbee Mar 05 '21 at 14:56

1 Answers1

0

You can "pivot" your data to support your desired plotting output. Here we set the rows as Year, columns as City, and values as AQI.

pivot = pd.pivot_table(
    data=df,
    index='Year',
    columns='City',
    values='AQI',
)
Year Ahmedabad Delhi Gurugram Lucknow Patna
2015 283.007605 297.024658 NaN NaN 349.407407
2016 282.717949 297.619178 NaN NaN 250.528701
2017 379.753623 NaN 281.401216 NaN 325.652778
2018 443.053221 248.367123 NaN 233.772603 NaN
2019 412.781250 230.720548 NaN NaN 217.626741
2020 214.681818 181.672131 NaN NaN 162.251366

Then you can plot this pivot table directly:

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

enter image description here


Old answer

Are you looking for the mean AQI per year? If so, you can do some pandas chaining, assuming your data is in a DataFrame df:

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

aqi_groupby_year

tdy
  • 36,675
  • 19
  • 86
  • 83
  • Thank you for the revert. However I am looking to group the like years together with the cities for the year on the x axis and AQI on the y axis. As you will see I have the AQI values for 3 cities for each year from 2015 till 2020. I would like to plot the 3 cities of each year together on the x axis , so this would mean all 3 cities for year 2015 together (with names of the cities on the x axis and AQI on the y axis) followed by the same for year 2016 and so on till 2020. Hope this helps clarify my aim – NCoder Mar 06 '21 at 19:35
  • Ok if I understand correctly, my edited answer should help. – tdy Mar 06 '21 at 20:40
  • 1
    Perfect this is exactly what I wanted. Thank you for your help. – NCoder Mar 06 '21 at 22:49