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

Pandas groupby结果用Plotly绘柱状图提示分组列不存在如何解决

报错原因

Pandas执行groupby(['Market']).sum()操作后,Market会从普通数据列转换为结果DataFrame的行索引,不再属于列名范畴。Pandas自带的plot方法默认会把行索引作为X轴数据源,所以之前的Matplotlib逻辑可以正常运行;但Plotly Express的柱状图接口默认仅从列名检索你指定的x参数值,自然会报找不到Market列的错误。

解决方法

提供3种可直接复用的方案,任选其一即可:

方案1:分组时禁止将分组键转为索引

在groupby方法中添加as_index=False参数,让Market保留为普通列:

import plotly.express as px

balance.loc[balance['Type'] == 'BUY', 'Total'] = -balance['Total']
# 仅修改groupby行,添加as_index=False
balance = balance.groupby(['Market'], as_index=False).sum().sort_values('Total', ascending=False)

fig = px.bar(balance, x='Market', y='Total')
# 可添加配置和原Matplotlib版本效果完全对齐
fig.update_layout(
    title='BALANCE CRIPTOMONEDAS',
    yaxis_title='USDT',
    xaxis_title='SÍMBOLO',
    width=600,
    height=500
)
fig.show()

方案2:绘图时直接指定X轴为行索引

不需要修改分组逻辑,直接把索引作为X轴数据源传入即可:

import plotly.express as px

balance.loc[balance['Type'] == 'BUY', 'Total'] = -balance['Total']
balance = balance.groupby(['Market']).sum().sort_values('Total',ascending=False)

# 仅修改px.bar的x参数为索引
fig = px.bar(balance, x=balance.index, y='Total')
fig.update_layout(
    title='BALANCE CRIPTOMONEDAS',
    yaxis_title='USDT',
    xaxis_title='SÍMBOLO',
    width=600,
    height=500
)
fig.show()

方案3:手动将行索引转回普通列

调用reset_index()方法把索引Market重新转为数据列:

import plotly.express as px

balance.loc[balance['Type'] == 'BUY', 'Total'] = -balance['Total']
balance = balance.groupby(['Market']).sum().sort_values('Total',ascending=False).reset_index()

fig = px.bar(balance, x='Market', y='Total')
fig.update_layout(
    title='BALANCE CRIPTOMONEDAS',
    yaxis_title='USDT',
    xaxis_title='SÍMBOLO',
    width=600,
    height=500
)
fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:51:01