You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Altair中使用带索引的Pandas DataFrame?

用带索引的pandas DataFrame绘制Altair图表的方法

Altair默认不会自动将pandas DataFrame的索引识别为数据列,因此需要手动处理才能将索引映射为x轴值,以下是两种常用方案:

方案1:重置索引为命名列(推荐)

直接通过pandas的reset_index()方法将索引转为普通命名列,之后即可在Altair的编码中直接引用该列名。如果不想修改原始DataFrame,可以创建临时副本操作:

import altair as alt

# 将索引转为名为'year'的列,生成临时DataFrame
df_for_altair = indexed_df.reset_index().rename(columns={'index': 'year'})

# 绘制示例堆叠条形图
chart = alt.Chart(df_for_altair).transform_fold(
    fold=['oil', 'electricity'],  # 对应你的能源载体列名
    as_=['energy_carrier', 'consumption']
).mark_bar().encode(
    x='year:O',  # :O 指定为序数类型
    y='consumption:Q',  # :Q 指定为定量类型
    color='energy_carrier:N'  # :N 指定为名义类型
).properties(width=500, title='年度能源消耗量')

chart.show()

方案2:不修改DataFrame,直接在Altair中处理

如果希望保留原始DataFrame的结构,可以在传入Altair时临时转换索引为列,本质和方案1逻辑一致,只是无需显式保存副本:

import altair as alt

# 直接在Chart构造时转换索引
chart = alt.Chart(indexed_df.reset_index().rename(columns={'index': 'year'})).transform_fold(
    fold=['oil', 'electricity'],
    as_=['energy_carrier', 'consumption']
).mark_bar().encode(
    x='year:O',
    y='consumption:Q',
    color='energy_carrier:N'
)

chart.show()

为什么直接用x='index'无效?

Altair只能识别DataFrame的列名,而pandas的索引默认不属于数据列范畴,因此无法直接通过x='index'引用。必须先将索引转为普通列才能被Altair识别。

内容的提问来源于stack exchange,提问作者Stefan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:46:26