Pandas df.pivot() function
df.pivot() is a member method of DataFrame, used toCreate a pivot table. It can reshape data into a new layout based on specified row index, column index, and value columns.
The difference between pivot_table() in Vue 2,pivot() does not support aggregation operations and requires the combination of row index and column index to be unique, otherwise an error will be raised.
Word meaning: pivot means 'rotate, pivot'; here it refers to the 'rotation' reshaping of data, which, like a Pivot table, can dynamically switch row and column dimensions.
Basic syntax and parameters
df.pivot() is an instance method of DataFrame, called via the dot operator.
Syntax format
DataFrame.pivot(index=None, columns, values=None)
Parameter Description
- Parameters:
index - Type: column name, label, list of labels, or None.
- Description: the column used as the row index of the new DataFrame. If None, the existing row index is used.
- Parameters:
columns - Type: column name or label.
- Description: Required parameter. The column used as the column index of the new DataFrame, used to expand unique values into column names.
- Parameters:
values - Type: column name, label, list of labels, or None.
- Description: the data column used to fill the DataFrame. If not specified, all columns except index and columns are used.
Function description
- Return Value: returns a new DataFrame, namely the pivot table.
- Limitation: If the combination of index and columns contains duplicate values, a ValueError will be raised. In this case, you should use
pivot_table(), which automatically performs aggregation.
Example
Let us thoroughly master df.pivot() through a series of examples from simple to complex.
Example 1: Basic usage - Creating a simple pivot table
Example
import
pandas
as
pd
1. Create sales data (each row is a product-region-sales combination)
sales
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'A'
,
'B'
,
'B'
,
'C'
,
'C'
]
,
'region'
:
[
'North'
,
'South'
,
'North'
,
'South'
,
'North'
,
'South'
]
,
'sales'
:
[
100
,
150
,
200
,
180
,
220
,
250
]
}
)
(
"=== Original sales data ==="
)
(
sales
)
2. Use df.pivot() to create a pivot table
Row index: product, column index: region, values: sales
pivot_result
=
sales.
pivot
(
index
=
'product'
,
columns
=
'region'
,
values
=
'sales'
)
(
"n=== df.pivot() pivot table ==="
)
(
pivot_result
)
Expected output:
=== 原始销售数据 ===
product region sales
0 A North 100
1 A South 150
2 B North 200
3 B South 180
4 C North 220
5 C South 250
=== df.pivot() 透视表 ===
region North South
product
A 100 150
B 200 180
C 220 250
Code analysis:
- The original data is in long format, with each row recording the sales of a product in a certain region.
pivot()Use the product column as the row index, the region column as the column index, and sales as the values.- The result is a clear two-dimensional table that allows intuitive comparison of sales of different products in different regions.
Example 2: Multiple value columns - Pivoting multiple metrics at once
You can pivot multiple numeric columns at the same time to obtain a richer data view.
Example
import
pandas
as
pd
1. Create data containing sales and quantity
sales
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'A'
,
'B'
,
'B'
,
'A'
,
'A'
,
'B'
,
'B'
]
,
'region'
:
[
'North'
,
'South'
,
'North'
,
'South'
,
'East'
,
'West'
,
'East'
,
'West'
]
,
'sales'
:
[
100
,
150
,
200
,
180
,
120
,
130
,
190
,
210
]
,
'quantity'
:
[
10
,
15
,
20
,
18
,
12
,
13
,
19
,
21
]
}
)
(
"=== Original data ==="
)
(
sales
)
2. Pivot only sales
(
"n=== Sales pivot table ==="
)
sales_pivot
=
sales.
pivot
(
index
=
'product'
,
columns
=
'region'
,
values
=
'sales'
)
(
sales_pivot
)
3. Pivot sales and quantity (do not specify values; use all numeric columns)
(
"n=== Multi-metric pivot ==="
)
multi_pivot
=
sales.
pivot
(
index
=
'product'
,
columns
=
'region'
)
(
multi_pivot
)
Expected output:
=== 原始数据 ===
product region sales quantity
0 A North 100 10
1 A South 150 15
2 B North 200 20
3 B South 180 18
4 A East 120 12
5 A West 130 13
6 B East 190 19
7 B West 210 21
=== 销售额透视表 ===
region East North South West
product
A 120 100 150 130
B 190 200 180 210
=== 多指标透视 ===
sales quantity
region East North South West East North South West
product
A 120 100 150 130 12 10 15 13
B 190 200 180 210 19 20 18 21
Code analysis:
- If not specified,
valuesthe parameter causes all columns except index and columns to be used. - Pivoting multiple columns produces a multi-level column index: the first level is the original column names, and the second level is the values of the columns parameter.
- This approach makes it easy to compare the performance of multiple metrics across different dimensions at the same time.
Example 3: Multi-level index - Using multiple columns as the row index
You can use multiple columns to create a pivot table with a hierarchical index.
Example
import
pandas
as
pd
1. Create data containing year, quarter, and product information
data
=
pd.
DataFrame
(
{
'year'
:
[
2023
,
2023
,
2023
,
2023
,
2024
,
2024
,
2024
,
2024
]
,
'quarter'
:
[
'Q1'
,
'Q1'
,
'Q2'
,
'Q2'
,
'Q1'
,
'Q1'
,
'Q2'
,
'Q2'
]
,
'product'
:
[
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
]
,
'sales'
:
[
100
,
150
,
200
,
180
,
220
,
250
,
230
,
270
]
}
)
(
"=== Original data ==="
)
(
data
)
2. Use multiple columns as the row index (in list form)
(
"n=== Multi-level row index pivot ==="
)
pivot_multi
=
data.
pivot
(
index
=
[
'year'
,
'quarter'
]
,
columns
=
'product'
,
values
=
'sales'
)
(
pivot_multi
)
3. Reset the index, converting to a normal DataFrame
(
"n=== After resetting the index ==="
)
pivot_reset
=
pivot_multi.
reset_index
(
)
(
pivot_reset
)
Expected output:
=== 原始数据 ===
year quarter product sales
0 2023 Q1 A 100
1 2023 Q1 B 150
值会抛出错误
- 这是 pivot() 和 pivot_table() 的关键区别:pivot() 要求数据唯一性,pivot_table() 会自动聚合重复值
Code analysis:
- Pass
index=['year', 'quarter']You can create a pivot table with a multi-level row index. - This format makes it easy to analyze the performance of different products by time dimension.
- Use
reset_index()You can convert a hierarchical index back to normal columns.
Note: If the original data contains the same index + columns combination,
pivot()will throwValueError: Index contains duplicate entries. In this case, you should usepivot_table(), which automatically aggregates duplicate values.
Common Pandas functions