pythonintermediate

Polars Pivot and Unpivot

Reshape a Polars DataFrame from long to wide (pivot) and wide to long (unpivot/melt).

python
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.