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.
123456789101112131415161718192021222324252627import 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)
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat