開始使用免費開始

百分位數與 partial 函式

在這個練習中,你會練習如何預先指定函式的參數,以便事先設定它的執行方式。你會用同一個 numpypercentile() 函式來計算多個資料的百分位數。

本練習屬於課程

Python 的時間序列資料機器學習

檢視課程

練習說明

  • functools 匯入 partial
  • 使用 partial() 透過串列生成式建立多個特徵產生器,用來計算資料的各種百分位數。
  • 使用我們替你定義的滾動視窗(prices_perc_rolling),用 percentile_functions 計算分位數。
  • 使用提供給你的程式碼將結果視覺化。

動手互動練習

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

# Import partial from functools
____
percentiles = [1, 10, 25, 50, 75, 90, 99]

# Use a list comprehension to create a partial function for each quantile
percentile_functions = [____(np.percentile, q=percentile) for percentile in percentiles]

# Calculate each of these quantiles on the data using a rolling window
prices_perc_rolling = prices_perc.rolling(20, min_periods=5, closed='right')
features_percentiles = prices_perc_rolling.____(____)

# Plot a subset of the result
ax = features_percentiles.loc[:"2011-01"].plot(cmap=plt.cm.viridis)
ax.legend(percentiles, loc=(1.01, .5))
plt.show()
編輯並執行程式碼