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
类构建,该类具有以下选项