Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.pivot() function

Pandas df.pivot() function

Pandas Common Functions Common Pandas functions


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

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


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

]

}

)

print

(

"=== Original sales data ==="

)

print

(

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'

)

print

(

"n=== df.pivot() pivot table ==="

)

print

(

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:

  1. The original data is in long format, with each row recording the sales of a product in a certain region.
  2. pivot() Use the product column as the row index, the region column as the column index, and sales as the values.
  3. 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

]

}

)

print

(

"=== Original data ==="

)

print

(

sales

)

2. Pivot only sales

print

(

"n=== Sales pivot table ==="

)

sales_pivot

=

sales.

pivot

(

index

=

'product'

,

columns

=

'region'

,

values

=

'sales'

)

print

(

sales_pivot

)

3. Pivot sales and quantity (do not specify values; use all numeric columns)

print

(

"n=== Multi-metric pivot ==="

)

multi_pivot

=

sales.

pivot

(

index

=

'product'

,

columns

=

'region'

)

print

(

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:

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

]

}

)

print

(

"=== Original data ==="

)

print

(

data

)

2. Use multiple columns as the row index (in list form)

print

(

"n=== Multi-level row index pivot ==="

)

pivot_multi

=

data.

pivot

(

index

=

[

'year'

,

'quarter'

]

,

columns

=

'product'

,

values

=

'sales'

)

print

(

pivot_multi

)

3. Reset the index, converting to a normal DataFrame

print

(

"n=== After resetting the index ==="

)

pivot_reset

=

pivot_multi.

reset_index

(

)

print

(

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:

Note: If the original data contains the same index + columns combination,pivot() will throw ValueError: Index contains duplicate entries. In this case, you should use pivot_table(), which automatically aggregates duplicate values.

Pandas Common Functions Common Pandas functions