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

如何将Pandas DataFrame整行内容作为散点图悬停注释并修复索引报错

报错原因

你出现IndexError的核心原因是代码逻辑错误:

  • x.target.index返回的是当前选中散点在对应scatter序列中的行索引,数值范围是0~len(df)-1,和DataFrame的行号一一对应
  • 你用这个行号去取仅包含8个元素的df.columns列表,自然触发索引越界
修复方案

你需要获取散点对应的DataFrame整行数据,按需求拼接所有字段的键值对即可,修改回调逻辑如下:
首先删除原来的cr1.connect和cr2.connect两行代码,替换为以下内容:

def show_row_info(sel):
    # 取当前点对应的df行
    row_data = df.iloc[sel.target.index]
    # 按要求拼接字段信息
    info_list = [f"{col} = {val}" for col, val in row_data.items()]
    sel.annotation.set_text("\n".join(info_list))
    # 可选:设置注释背景为白色半透明,避免遮挡图表内容
    sel.annotation.get_bbox_patch().set(facecolor="white", alpha=0.9)

# 给两个子图的cursor都绑定回调
cr1.connect("add", show_row_info)
cr2.connect("add", show_row_info)

修改完成后运行代码,鼠标悬停在散点上就会显示你需要的全字段标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:06:02