Adding a custom expression
Your team frequently calculates per-listener metrics across different reports. To make this pattern even more reusable, create a custom expression that can be chained like any built-in Polars method.
polars is loaded as pl. The DataFrame spotify is available with album streaming data.
本练习是课程的一部分
Data Transformation with Polars
练习说明
- Define
per_listener()to divide its input by themonthly_listenerscolumn. - Attach the function to
pl.Exprto make it chainable. - Apply the custom method on the
streamscolumn.
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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())