I am trying to calculate the means per month and year and plot it in a seaborn heatmap:
city_id NO2 O3 season
basetime
2015-01-01 AQ003 7.80 63.02 winter
2015-01-02 AQ003 18.51 52.76 winter
2015-01-03 AQ003 36.52 21.13 winter
2015-01-04 AQ003 31.92 29.80 winter
2015-01-05 AQ003 11.53 56.84 winter
So this was my idea:
year = airquality_athen.index.year.rename("year")
month = airquality_athen.index.month.rename("month")
monthly_means_per_year = airquality_athen.groupby([year, month]).mean()
seven_point_five = monthly_means_per_year.pivot("month", "year", "NO2")
ax = sns.heatmap(seven_point_five)
So the problem is that i don't know how to handle datetime objects when it comes to using them in a plot. (I am getting key error: 'month') I wanted it to look like the fourth plot on this:
https://seaborn.pydata.org/generated/seaborn.heatmap.html#seaborn.heatmap
CodePudding user response:
Try this:
df.index = pd.to_datetime(df.index)
df['year'] = df.index.year
df['month'] = df.index.month
monthly_means_per_year = df.groupby(['year', 'month'], as_index=False).mean()
seven_point_five = monthly_means_per_year.pivot("month", 'year', "NO2")
ax = sns.heatmap(seven_point_five)