Get startedGet started for free

Pivoting a DataFrame

You want to convert the Spotify data from long format to wide format in order to compare the number of streams for each artist in each year.

The spotify_df DataFrame is available for you and has been modified to get the number of streams for each artist in each year in artist_year_df.

This exercise is part of the course

Introduction to Polars

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

artist_year_df = spotify_df.group_by("artist", "year").agg(pl.col("streams").sum())

pivoted_df = (
    artist_year_df
    # Pivot with artists as rows, years as columns and streams as values
    .pivot(
        on=____,
        index=____,
        values=____
    )
)

print(pivoted_df)
Edit and Run Code