พล็อตแนวโน้มรายเดือนและรายปี
เช่นเดียวกับที่เห็นในบทที่ 2 เมื่อ index ของ DataFrame เป็นชนิด datetime จะสามารถดึงข้อมูลวัน เดือน หรือปีของแต่ละวันที่ใน index ได้โดยตรง เพื่อเป็นการทบทวน สามารถดึงปีของแต่ละวันที่ใน index ได้โดยใช้แอตทริบิวต์ .index.year จากนั้นใช้เมธอด .groupby() และ .mean() เพื่อคำนวณค่าเฉลี่ยรายปีของแต่ละอนุกรมเวลาใน DataFrame:
index_year = df.index.year
df_by_year = df.groupby(index_year).mean()
ตอนนี้ให้นำสิ่งที่เรียนมาประยุกต์ใช้เพื่อแสดงค่าเฉลี่ยรวมของแต่ละอนุกรมเวลาใน DataFrame jobs
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การแสดงภาพข้อมูล Time Series ด้วย Python
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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()