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

使用Plotly绘制堆叠条形图报错hasattr(): attribute name must be string

解决Plotly堆叠条形图报错"hasattr(): attribute name must be string"的方案
  • 错误根源:访问多级索引列的方式有误。当数据框为多级列索引时,不能直接用gdp['IMF[1][13]', 'Estimate'],需将列名组合成元组进行访问。

  • 修改后的代码:

import plotly.express as px

# 用元组指定多级列索引
fig = px.bar(gdp, x='UN Region', y=('IMF[1][13]', 'Estimate'), color='Country/Territory')
fig.show()
  • 备选写法(更清晰定位列):
import plotly.express as px

# 明确指定目标列
target_column = ('IMF[1][13]', 'Estimate')
fig = px.bar(gdp, x='UN Region', y=gdp.loc[:, target_column], color='Country/Territory')
fig.show()
  • 额外提示:可通过print(gdp.columns)查看数据框的列结构,确认是否为多级索引,避免因列名格式问题引发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:12:08