開始使用免費開始

顯示彙總後的數值

有時你需要以更高的彙總層級來呈現資料。例如,co2_levels 是每週資料,但你可能需要依一年中的月份來彙總並顯示其數值。對於像 co2_levels 這樣索引為 datetime 型別的 DataFrame,你可以擷取索引中每個日期的年份:

# 從 df DataFrame 的每個日期擷取年份
index_year = df.index.year

若要從 df 的索引日期中擷取月份或日期,分別使用 df.index.monthdf.index.day。 接著,你可以將從 co2_levels 的索引擷取出的年份搭配 groupby 函式,計算每年的 CO2 平均濃度:

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

本練習屬於課程

使用 Python 視覺化時間序列資料

檢視課程

練習說明

  • co2_levels DataFrame 的索引中擷取每個日期的月份,並指派給變數 index_month
  • 使用 pandas 函式庫的 groupbymean,計算 co2_levels 中依月份分組的 CO2 平均濃度,並指派給新的 DataFrame mean_co2_levels_by_month
  • 以座標軸刻度字型大小 6 繪製 mean_co2_levels_by_month DataFrame 的數值。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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()
編輯並執行程式碼