ComenzarEmpieza gratis

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.

Este ejercicio forma parte del curso

Data Transformation with Polars

Ver curso

Instrucciones del ejercicio

  • Define per_listener() to divide its input by the monthly_listeners column.
  • Attach the function to pl.Expr to make it chainable.
  • Apply the custom method on the streams column.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# 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())
Editar y ejecutar código