カスタム式を追加する
チームでは、さまざまなレポートでリスナーあたりの指標を頻繁に計算しています。このパターンをさらに再利用しやすくするため、組み込みの Polars メソッドと同じようにチェーンできるカスタム式を作成しましょう。
polars は pl として読み込まれています。アルバムのストリーミングデータを含む DataFrame spotify が利用できます。
この演習はコースの一部です
Data Transformation with 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())