CommencerCommencer gratuitement

Plot monthly and yearly trends

Like we saw in Chapter 2, when the index of a DataFrame is of the datetime type, it is possible to directly extract the day, month or year of each date in the index. As a reminder, you can extract the year of each date in the index using the .index.year attribute. You can then use the .groupby() and .mean() methods to compute the mean annual value of each time series in your DataFrame:

index_year = df.index.year
df_by_year = df.groupby(index_year).mean()

You will now apply what you have learned to display the aggregate mean values of each time series in the jobs DataFrame.

Cet exercice fait partie du cours

Visualizing Time Series Data in Python

Afficher le cours

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Extract the month from the index of jobs
index_month = ____.____.____

# Compute the mean unemployment rate for each month
jobs_by_month = ____.____(____).____()

# Plot the mean unemployment rate for each month
ax = ____.plot(fontsize=6, linewidth=1)

# Set axis labels and legend
ax.set_xlabel('Month', fontsize=10)
ax.set_ylabel('Mean unemployment rate', fontsize=10)
ax.legend(bbox_to_anchor=(0.8, 0.6), fontsize=10)
plt.show()
Modifier et exécuter le code