pythonintermediate
Polars Pivot and Unpivot
Reshape a Polars DataFrame from long to wide (pivot) and wide to long (unpivot/melt).
pythonPress ⌘/Ctrl + Shift + C to copy
import polars as pl
df_long = pl.DataFrame({'country':['US','US','UK','UK'],'year':[2022,2023,2022,2023],'sales':[100,120,80,95]})
# Long -> Wide
df_wide = df_long.pivot(values='sales', index='country', columns='year')
print('Wide:'); print(df_wide)
# Wide -> Long
df_back = df_wide.unpivot(index='country', variable_name='year', value_name='sales')
print('Long:'); print(df_back)Use Cases
- data reshaping
- report pivoting
- tidy data conversion
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Pandas Pivot and Unpivot Reshaping
Reshape DataFrames between wide and long formats using pivot, melt, and stack operations.
Best for: Reshaping data for reporting dashboards
#pandas#pivot
pythonintermediate
Pandas MultiIndex Stack & Unstack
Work with hierarchical MultiIndex DataFrames: pivoting with stack/unstack and cross-sectional slicing.
Best for: panel data
#pandas#multiindex
pythonbeginner
Pandas Wide to Long (melt)
Transform a wide-format DataFrame into long format using pd.melt for analytics and visualisation.
Best for: pivot table conversion
#pandas#melt
pythonintermediate
Polars Lazy Query — Fast DataFrame Processing
Use Polars lazy evaluation for high-performance data transformations that outperform pandas.
Best for: High-performance data processing replacing pandas
#polars#dataframe