Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Reshaping Layouts | Combining, Aggregating
Data Wrangling with Polars

Reshaping Layouts

Swipe to show menu

Reshaping your data is often essential for effective analysis, especially when you need to compare values across categories or prepare your data for visualization. In Polars, you can use pivot and melt (unpivot) operations to transform your DataFrame between wide and long formats. Suppose you have a DataFrame called games_df with columns: game_title, developer, and steam_deck_status. You want to see how many games each developer has in each Steam Deck compatibility category.

To do this, you can pivot the data so that each row represents a developer, each column represents a unique steam_deck_status, and the cell values show the count of games. Afterwards, you might want to unpivot (melt) the wide table back to a long format for further processing or visualization.

123456789101112131415161718192021222324252627
import polars as pl # Sample data games_df = pl.DataFrame({ "game_title": ["Game A", "Game B", "Game C", "Game D", "Game E", "Game F"], "developer": ["Dev1", "Dev2", "Dev1", "Dev2", "Dev3", "Dev1"], "steam_deck_status": ["Verified", "Playable", "Playable", "Verified", "Unsupported", "Playable"] }) # Pivot: count games per developer by steam_deck_status pivoted = games_df.pivot( values="game_title", index="developer", columns="steam_deck_status", aggregate_function="count" ) print("Pivoted (wide format):") print(pivoted) # Unpivot (melt): go back to long format melted = pivoted.melt( id_vars="developer", variable_name="steam_deck_status", value_name="game_count" ) print("\nUnpivoted (long format):") print(melted)
question mark

Which of these statements correctly describes the difference between pivot and melt in data wrangling?

Select all correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 5

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 2. Chapter 5
some-alt