Long to wide reshaping
Convert records with category and measure fields into a wide matrix for inspection or downstream processing.
Pandas · Module
Reshapes a DataFrame into a matrix using selected fields for its index, columns, and values. It does not aggregate duplicate index-column combinations.
DataFrame.pivot reshapes long-form data into a matrix by selecting fields for the output index, columns, and cell values. It requires each index-and-column pair to identify one value; use pivot_table when duplicate pairs need aggregation.
DataFrame.pivot(*, columns, index=<no_default>, values=<no_default>)| Name | Type | Description |
|---|---|---|
columns | Hashable or a sequence of the previous | Column to use to make new frame’s columns. |
index | Hashable or a sequence of the previous, optional | Column to use to make new frame’s index. If not given, uses existing index. |
values | Hashable or a sequence of the previous, optional | Column(s) to use for populating new frame’s values. If not specified, all remaining columns will be used and the result will have hierarchically indexed columns. |
DataFrame
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B"],
"quarter": ["Q1", "Q2", "Q1"],
"revenue": [10, 12, 9],
})
wide = sales.pivot(index="store", columns="quarter", values="revenue")
print(wide)
Uses store values as rows, quarter values as columns, and revenue as the resulting cells.
Convert records with category and measure fields into a wide matrix for inspection or downstream processing.
Keep the source index as the output row axis while spreading one field across columns.
Expose several measures at once when a single index-column pair maps to multiple value fields.
The method reshapes a DataFrame using unique values from the chosen index and columns to form the result axes. The selected values populate the cells.
Follow-up: What happens when a pair is not unique? pivot cannot aggregate it; choose pivot_table when aggregation is required.
columns is required and identifies the field whose distinct values become output columns. index is optional; when omitted, the existing DataFrame index supplies the output index.
Follow-up: How can several fields define an axis? Pass a sequence for index or columns, producing a hierarchical axis when appropriate.
values is optional and selects the column or columns used to populate the result. If omitted, all columns not used for index or columns are included, yielding hierarchically indexed columns.
Follow-up: How would you create a summarized cross-tabulation? Use pivot_table and provide an aggregation function.
DataFrame.pivot_tablepandas.pivotpandas.pivot_table