加入自訂運算式
你的團隊經常在不同報表中計算「每位聽眾」的指標。為了讓這個模式更容易重複使用,請建立一個自訂運算式,能像任何內建的 Polars 方法一樣被串接。
polars 已以 pl 載入。資料框 spotify 已可使用,內容為專輯的串流資料。
本練習屬於課程
使用 Polars 進行資料轉換
練習說明
- 定義
per_listener(),將其輸入除以monthly_listeners欄位。 - 將該函式掛到
pl.Expr上以支援串接。 - 在
streams欄位上套用這個自訂方法。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define the per_listener function
def per_listener(input):
return ____ / pl.col("____")
# Attach the function to pl.Expr
pl.Expr.____ = ____
# Use the custom method on the streams column
result = spotify.with_columns(
pl.col("____").____().alias("streams_per_listener")
)
print(result.head())