Altair中transform_aggregate与编码聚合结果不一致问题排查
Altair中transform_aggregate与编码式聚合结果不一致问题
我正在对比Altair中transform_aggregate与编码式聚合的工作机制,发现二者输出结果不一致,不确定是否正确使用了transform_aggregate。以下是我的测试示例:
数据生成代码
import altair as alt import pandas as pd import numpy as np T = ["Hot", "Cold"] P = ["high","medium","low"] A = ["0-50","50+"] c = [[t, p, a] for t in T for p in P for a in A] df = pd.DataFrame(c, columns=["Temperature", "Precipitation", "AgeGroup"]) df["Value"] = [int(x) for x in np.random.sample(df.shape[0]) * 10] df
生成的数据集
| Temperature | Precipitation | AgeGroup | Value |
|---|---|---|---|
| Hot | high | 0-50 | 0 |
| Hot | high | 50+ | 3 |
| Hot | medium | 0-50 | 4 |
| Hot | medium | 50+ | 7 |
| Hot | low | 0-50 | 9 |
| Hot | low | 50+ | 0 |
| Cold | high | 0-50 | 9 |
| Cold | high | 50+ | 1 |
| Cold | medium | 0-50 | 2 |
| Cold | medium | 50+ | 6 |
| Cold | low | 0-50 | 4 |
| Cold | low | 50+ | 1 |
预期的Python聚合结果
我希望在Altair中复现以下两种Pandas聚合结果:
按Temperature和Precipitation分组求和
df.groupby(["Temperature","Precipitation"]).agg( {"Value":"sum"} )
对应的聚合结果:
| Temperature | Precipitation | Value |
|---|---|---|
| Cold | high | 10 |
| Cold | low | 5 |
| Cold | medium | 8 |
| Hot | high | 3 |
| Hot | low | 9 |
| Hot | medium | 11 |
按Precipitation分组求和
df.groupby(["Precipitation"]).agg( {"Value":"sum"} )
对应的聚合结果:
| Precipitation | Value |
|---|---|
| high | 13 |
| low | 14 |
| medium | 19 |
编码式聚合的正确实现
在Altair中,使用编码式聚合可以成功复现预期结果:
热力图示例
alt.Chart(df).mark_rect().encode( y="Temperature:N", x="Precipitation:N", color=alt.Color("sum(Value):Q"), tooltip=[alt.Tooltip("sum(Value):Q")] )
得到对应正确的热力图结果。
柱状图示例
alt.Chart(df).mark_bar().encode( y="sum(Value):Q", x="Precipitation:N", )
得到对应正确的柱状图结果。
transform_aggregate的错误实现及问题
但使用transform_aggregate的代码无法得到正确结果,total_value字段返回Null值:
热力图错误示例
alt.Chart(df).mark_rect().encode( x="Temperature:N", y="Precipitation:N", color="total_value:Q" ).transform_aggregate( total_val="sum(Value)", groupby=["Temperature","Precipitation"])
得到的结果中total_value字段为Null,无法正确显示聚合值。
柱状图错误示例
alt.Chart(df).mark_bar().encode( x="Precipitation", y="total_value:Q" ).transform_aggregate( total_val='sum(Value)', groupby=["Precipitation"])
得到的结果中total_value字段为Null,无法正确显示聚合值。
运行环境
- Python 3.11.4
- Altair 5.1.1
内容的提问来源于stack exchange,提问作者Matt0867
相关产品推荐
相关产品推荐

