Pivot#

简而言之,pivot 转换是一种无需任何预处理即可将长格式数据直接转换为宽格式数据的方法(详见 长格式与宽格式数据)。Pivot 转换对于创建矩阵或交叉表数据非常有用,它与 Fold 转换的作用相反。

以下是一个使用奥运奖牌数据的示例

import altair as alt
import pandas as pd

df = pd.DataFrame.from_records([
    {"country": "Norway", "type": "gold", "count": 14},
    {"country": "Norway", "type": "silver", "count": 14},
    {"country": "Norway", "type": "bronze", "count": 11},
    {"country": "Germany", "type": "gold", "count": 14},
    {"country": "Germany", "type": "silver", "count": 10},
    {"country": "Germany", "type": "bronze", "count": 7},
    {"country": "Canada", "type": "gold", "count": 11},
    {"country": "Canada", "type": "silver", "count": 8},
    {"country": "Canada", "type": "bronze", "count": 10}
])

alt.Chart(df).transform_pivot(
    'type',
    groupby=['country'],
    value='count'
).mark_bar().encode(
    x='gold:Q',
    y='country:N',
)

pivot 转换与其他 Altair 语法元素结合使用时,可以实现一些非常有趣的图表类型。例如,在此处我们使用 pivot 为多条线上的值创建单个工具提示

import altair as alt
from vega_datasets import data

source = data.stocks()
base = alt.Chart(source).encode(x='date:T')
columns = sorted(source.symbol.unique())
selection = alt.selection_point(
    fields=['date'], nearest=True, on='pointerover', empty=False, clear='pointerout'
)

lines = base.mark_line().encode(y='price:Q', color='symbol:N')
points = lines.mark_point().transform_filter(selection)

rule = base.transform_pivot(
    'symbol', value='price', groupby=['date']
).mark_rule().encode(
    opacity=alt.when(selection).then(alt.value(0.3)).otherwise(alt.value(0)),
    tooltip=[alt.Tooltip(c, type='quantitative') for c in columns]
).add_params(selection)

lines + points + rule

转换选项#

transform_pivot() 方法基于 PivotTransform 类构建,该类具有以下选项

点击显示表格

属性

类型

描述

groupby

数组(FieldName)

可选的数据字段,用于分组。如果未指定,将使用包含所有数据对象的单个组。

limit

数字

一个可选参数,指示要生成的最大 pivoted 字段数。默认值 (0) 表示没有限制。在强制执行限制之前, pivoted pivot 名称会按升序排序。 默认值: 0

op

AggregateOp

应用于分组 value 字段值的聚合操作。 默认值: sum

pivot

FieldName

要进行 pivot 转换的数据字段。此字段的唯一值将成为输出流中的新字段名。

value

FieldName

用于填充 pivoted 字段的数据字段。此字段的聚合值将成为新 pivoted 字段的值。