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

Pandas DataFrame.pivot_table() function

Pandas DataFrame.pivot_table() function

Pandas Common Functions Common Pandas functions


df.pivot_table() is a member method of DataFrame, used tocreate a pivot table. It is an pivot() enhanced version that supports aggregation operations and can handle duplicate row-index and column-index combinations.

A pivot table is one of the most commonly used tools in data analysis; it can group, summarize, and reshape data from different perspectives, making it easier to discover patterns and trends in the data.

Word meaning: pivot_table means 'pivot table', a table that can dynamically change data layout and supports automatic aggregation of duplicate data.


Basic syntax and parameters

df.pivot_table() is an instance method of DataFrame, called via the dot operator.

Syntax format



DataFrame.pivot_table(values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All')

Parameter Description

- Type: column name, label, list of labels, or None. - Description: the column used as the row index. It can be a single column or multiple columns (a list); multiple columns create a hierarchical index. - Type: column name or label. - Description: the column used as the column index, used to expand unique values into column names. - Type: column name, label, list of labels, or None. - Description: the numeric columns to aggregate. If not specified, all numeric columns are aggregated. - Type: function, string, or list of functions. - Description: the aggregation function. Common values include `'sum'` (sum), `'mean'` (mean, the default), `'count'` (count), `'min'` (min), `'max'` (max), `'median'` (median), `'std'` (standard deviation), etc. - Type: scalar or None. - Description: the value used to fill missing values. Defaults to None, which preserves NaN. - Type: boolean. - Description: whether to add row and column totals. Defaults to False. When set to True, summary data is added at the end of rows and columns. - Type: string. - Description: the name of the total row/column, defaults to 'All'. Only effective when margins=True.

Function description


Example

Let us thoroughly master df.pivot_table() 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

sales

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'B'

,

'C'

,

'A'

,

'B'

,

'C'

,

'A'

,

'B'

,

'C'

,

'A'

,

'B'

,

'C'

]

,

   

'region'

:

[

'North'

,

'North'

,

'North'

,

'South'

,

'South'

,

'South'

,

'East'

,

'East'

,

'East'

,

'West'

,

'West'

,

'West'

]

,

   

'sales'

:

[

100

,

150

,

200

,

180

,

170

,

160

,

190

,

200

,

210

,

220

,

230

,

240

]

}

)

print

(

"=== Sales data ==="

)

print

(

sales

)

2. Create a pivot table - summarize sales by product and region (the default aggregation function is mean)

pivot

=

sales.

pivot_table

(

values

=

'sales'

,

index

=

'product'

,

columns

=

'region'

,

aggfunc

=

'sum'

)

print

(

"n=== df.pivot_table() sales pivot table (sum)==="

)

print

(

pivot

)

Expected output:



=== 销售数据 ===

    product  region  sales

0         A   North    100

1         B   North    150

2         C   North    200

3         A   South    180

4         B   South    170

5         C   South    160

6         A   East    190

7         B   East    200

8         C   East    210

9         A   West    220

10        B   West    230

11        C   West    240



=== df.pivot_table() 销售透视表(求和)===

region   East  North  South  West

product

A         190    100    180   220

B         200    150    170   230

C         210    200    160   240

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_table() Use product as the row index, region as the column index, and sales as the values.
  3. Use aggfunc='sum' Sum the sales for aggregation.
  4. The result is a clear two-dimensional table, making it easy to compare the sales performance of different products in different regions.

Example 2: Using different aggregation functions

aggfunc The parameter can specify multiple aggregation methods to analyze data.

Example

import

pandas

as

pd

import

numpy

as

np

1. Create richer sales data (each product has multiple records)

sales

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

]

,

   

'region'

:

[

'North'

,

'North'

,

'South'

,

'South'

,

'East'

,

'East'

,

'West'

,

'West'

,

'North'

,

'South'

]

,

   

'sales'

:

[

100

,

150

,

200

,

180

,

190

,

200

,

220

,

230

,

110

,

190

]

,

   

'quantity'

:

[

10

,

15

,

20

,

18

,

19

,

20

,

22

,

23

,

11

,

19

]

}

)

print

(

"=== Sales data ==="

)

print

(

sales

)

2. Calculate the average sales (default aggregation function)

print

(

"n=== Average sales ==="

)

mean_result

=

sales.

pivot_table

(

values

=

'sales'

,

index

=

'product'

,

columns

=

'region'

,

aggfunc

=

'mean'

)

print

(

mean_result.

round

(

1

)

)

3. Use multiple aggregation functions at the same time (pass a dictionary)

print

(

"n=== Multiple aggregation functions ==="

)

multi_agg

=

sales.

pivot_table

(

    values

=

'sales'

,

    index

=

'product'

,

    columns

=

'region'

,

    aggfunc

=

{

'sales'

:

[

'sum'

,

'mean'

,

'max'

]

}

)

print

(

multi_agg

)

4. Use different aggregation functions for different columns

print

(

"n=== Different aggregations for different columns ==="

)

diff_agg

=

sales.

pivot_table

(

    values

=

[

'sales'

,

'quantity'

]

,

    index

=

'product'

,

    columns

=

'region'

,

    aggfunc

=

{

'sales'

:

'sum'

,

'quantity'

:

'mean'

}

)

print

(

diff_agg

)

Expected output:



=== 销售数据 ===

   product  region  sales quantity

0        A   North    100       10

1        B   North    150       15

2        A   South    200       20

3        B   South    180       18

4        A   East    190       19

5        B   East    200       20

6        A   West    220       22

7        B   West    230       23

8        A   North    110       11

9        B   South    190       19



=== 销售额平均值 ===

region   East  North  South  West

product

A       190.0  105.0  200.0  220.0

B       200.0  150.0  185.0  230.0



=== 多聚合函数 ===

        sales

          sum          mean  max

region  East North South West East North South West East North South West

product

A       190  210   200  220   190  105   200  220   190  110   200  220

B       200  150   370  230   200  150   185  230   200  150   190  230



=== 不同列不同聚合 ===

        sales        quantity

region   East North South West  East North South West

product

A         190  210   200  220  19.0  10.5  20.0  22.0

B         200  150   370  230  20.0  15.0  18.5  23.0

Code analysis:

Example 3: Using margins to add totals

Use margins The parameter can add row and column totals, making it easy to view summary data.

Example

import

pandas

as

pd

1. Create sales data

sales

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

]

,

   

'region'

:

[

'North'

,

'North'

,

'South'

,

'South'

,

'East'

,

'East'

,

'West'

,

'West'

]

,

   

'sales'

:

[

100

,

150

,

200

,

180

,

190

,

200

,

220

,

230

]

}

)

2. Pivot table without totals

print

(

"=== No totals ==="

)

no_margins

=

sales.

pivot_table

(

values

=

'sales'

,

index

=

'product'

,

columns

=

'region'

,

aggfunc

=

'sum'

)

print

(

no_margins

)

3. Add row and column totals

print

(

"n=== Add totals (margins=True) ==="

)

with_margins

=

sales.

pivot_table

(

    values

=

'sales'

,

    index

=

'product'

,

    columns

=

'region'

,

    aggfunc

=

'sum'

,

    margins

=

True

)

print

(

with_margins

)

4. Customize the total name

print

(

"n=== Custom total name ==="

)

custom_name

=

sales.

pivot_table

(

    values

=

'sales'

,

    index

=

'product'

,

    columns

=

'region'

,

    aggfunc

=

'sum'

,

    margins

=

True

,

    margins_name

=

'Total'

)

print

(

custom_name

)

5. Pivot table with a multi-level row index

print

(

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

)

multi_index

=

sales.

pivot_table

(

    values

=

'sales'

,

    index

=

[

'product'

,

'region'

]

,

    aggfunc

=

'sum'

)

print

(

multi_index

)

Expected output:



=== 无合计 ===

region   East  North  South  West

product

A         190    100    200   220

B         200    150    180   230



=== 添加合计 (margins=True) ===

region   East  North  South  West   All

product

A         190    100    200   220   710

B         200    150    180   230   760

All       390    250    380   450  1470



=== 自定义合计名称 ===

region   East North South West   总计

product

A       190  100   200  220    710

B       200  150   180  230    760

总计     390  250   380  450   1470

Code analysis:

Example 4: Using fill_value to handle missing values

Use fill_value The parameter can fill missing values produced after pivoting.

Example

import

pandas

as

pd

import

numpy

as

np

1. Create data (some product-region combinations do not exist)

sales

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'B'

,

'A'

,

'B'

]

,

   

'region'

:

[

'North'

,

'North'

,

'South'

,

'South'

]

,

   

'sales'

:

[

100

,

150

,

200

,

180

]

}

)

print

(

"=== Original data ==="

)

print

(

sales

)

2. Do not fill missing values (default)

print

(

"n=== Do not fill missing values ==="

)

no_fill

=

sales.

pivot_table

(

values

=

'sales'

,

index

=

'product'

,

columns

=

'region'

)

print

(

no_fill

)

3. Fill missing values with 0

print

(

"n=== Fill missing values with 0 ==="

)

fill_zero

=

sales.

pivot_table

(

    values

=

'sales'

,

    index

=

'product'

,

    columns

=

'region'

,

    fill_value

=

0

)

print

(

fill_zero

)

4. Demonstrate automatic aggregation of duplicate values

data_with_duplicates

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'A'

,

'B'

,

'B'

,

'A'

]

,

   

'region'

:

[

'North'

,

'North'

,

'South'

,

'South'

,

'North'

]

,

   

'sales'

:

[

100

,

120

,

200

,

180

,

90

]

}

)

print

(

"n=== Duplicate value data ==="

)

print

(

data_with_duplicates

)

print

(

"n=== Automatic aggregation (pivot raises an error, pivot_table sums automatically)==="

)

auto_agg

=

data_with_duplicates.

pivot_table

(

    values

=

'sales'

,

    index

=

'product'

,

    columns

=

'region'

,

    aggfunc

=

'sum'

)

print

(

auto_agg

)

Expected output:



=== 原始数据 ===

  product  region  sales

0       A   North    100

1       B   North    150

2       A   South    200

3       B   South    180



=== 不填充缺失值 ===

region   North  South

product

A         100.0  200.0

B         150.0  180.0



=== 填充缺失值为0 ===

region  North  South

product

A         100   200

B         150   180



=== 重复值数据 ===

  product  region  sales

0       A   North    100

1       A   North    120

2       B   South    200

3       B   South    180

4       A   North    90



=== 自动聚合(pivot会报错,pivot_table自动求和)===

region   North  South

product

A         310     NaN

B         NaN    380

Code analysis:

Notes

Important note:

  • pivot_table() The difference between pivot() The main difference lies in how duplicate values are handled: pivot_table aggregates automatically, while pivot raises an error.
  • When values When the parameter is not specified, all numeric columns are aggregated.
  • margins The total rows/columns added by the parameter affect subsequent data processing, so take care when using it.
  • When processing large-scale data, pivot_table may consume a lot of memory, so mind the data volume.

  • Pandas Common Functions Common Pandas functions