เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

แสดงค่าข้อมูลแบบรวมกลุ่ม

บางครั้งอาจจำเป็นต้องแสดงข้อมูลในรูปแบบที่รวมกลุ่มไว้แล้ว เช่น ข้อมูล co2_levels มีความละเอียดรายสัปดาห์ แต่อาจต้องการแสดงค่าที่รวมกลุ่มตามเดือนของปีแทน สำหรับชุดข้อมูลอย่าง DataFrame co2_levels ที่ใช้ index ประเภท datetime สามารถดึงปีจากแต่ละวันที่ใน index ได้ดังนี้:

# extract of the year in each dates of the df DataFrame
index_year = df.index.year

หากต้องการดึงเดือนหรือวันจากวันที่ใน index ของ DataFrame df ให้ใช้ df.index.month และ df.index.day ตามลำดับ จากนั้นสามารถนำปีที่ดึงมาจาก index ของ DataFrame co2_levels มาใช้ร่วมกับฟังก์ชัน groupby เพื่อคำนวณค่าเฉลี่ย CO2 รายปีได้:

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

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การแสดงภาพข้อมูล Time Series ด้วย Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ดึงค่าเดือนจากแต่ละวันที่ใน index ของ DataFrame co2_levels แล้วกำหนดค่าดังกล่าวให้กับตัวแปรชื่อ index_month
  • ใช้ฟังก์ชัน groupby และ mean จากไลบรารี pandas เพื่อคำนวณค่าเฉลี่ย CO2 รายเดือนจาก DataFrame co2_levels แล้วกำหนดผลลัพธ์ให้กับ DataFrame ใหม่ชื่อ mean_co2_levels_by_month
  • พล็อตค่าจาก DataFrame mean_co2_levels_by_month โดยกำหนดขนาดตัวอักษรของ axis ticks เป็น 6

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Get month for each dates in the index of co2_levels
index_month = ____.index.____

# Compute the mean CO2 levels for each month of the year
mean_co2_levels_by_month = co2_levels.____(____).____()

# Plot the mean CO2 levels for each month of the year
mean_co2_levels_by_month.____

# Specify the fontsize on the legend
plt.legend(fontsize=10)

# Show plot
plt.show()
แก้ไขและรันโค้ด