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

遍历Pandas DataFrame每行取首列触发IndexingError的排查与解决

问题:遍历Pandas行绘制基因时间回归图时触发IndexingError

原代码遍历DataFrame行绘制每个基因的时间回归图时,出现IndexingError: Too many indexers错误,核心问题在于对iterrows()返回的Series使用了错误的索引方式。

错误原因

df5.iterrows()返回的row是一维Series,仅支持单维度索引(如row['0']),而原代码中j.iloc[:,0]是二维索引语法,仅适用于DataFrame,直接套用到Series上会触发索引数量过多的错误。此外,原代码试图用单行Series绘制散点图的思路不符合Plotly的要求——Plotly需要结构化的列数据来映射x、y等参数。

修正方案

需要将每个基因的多时间点数据转换为长格式DataFrame,让Plotly能正确识别字段映射。以下是修正后的完整代码:

import pandas as pd
import plotly.express as px
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# 保留原数据划分与模型训练代码
train_idx, test_idx = train_test_split(df5.index, test_size=.25, random_state=0)
df5["split"] = "train"
df5.loc[test_idx, "split"] = "test"

X = df5.iloc[:, 1:-1]
y = df5.iloc[:, 0]

X_train = df5.loc[train_idx, ["4", "8", "12", "24", "48"]]
y_train = df5.loc[train_idx, "0"]

model = LinearRegression()
model.fit(X_train, y_train)
df5['prediction'] = model.predict(X)

# 定义所有时间列
time_cols = ["0", "4", "8", "12", "24", "48"]

# 遍历每个基因生成回归图
for gene_name, row in df5.iterrows():
    # 构建当前基因的长格式数据:时间、真实表达值、预测值、分组
    gene_data = []
    for time in time_cols:
        gene_data.append({
            "time": time,
            "actual_expression": row[time],
            "predicted_expression": row["prediction"],
            "split": row["split"]
        })
    gene_df = pd.DataFrame(gene_data)
    
    # 绘制散点回归图
    fig = px.scatter(gene_df,
                     x="actual_expression",
                     y="predicted_expression",
                     marginal_x="histogram",
                     marginal_y="histogram",
                     color="split",
                     trendline="ols",
                     title=f"基因 {gene_name} 真实值vs预测值")
    fig.update_traces(histnorm='probability', selector={'type':'histogram'})
    # 添加y=x参考线(预测完美时的基准线)
    fig.add_shape(type="line",
                  line=dict(dash='dash', color='gray'),
                  x0=df5[time_cols].min().min(),
                  y0=df5["prediction"].min(),
                  x1=df5[time_cols].max().max(),
                  y1=df5["prediction"].max())
    fig.show()

代码说明

  1. 长格式数据构建:将每个基因的多个时间点表达值拆分为多行,每行对应一个时间点的真实值、预测值和分组信息,符合Plotly的数据输入要求。
  2. 索引修正:直接通过列名row[time]提取一维Series中的值,避免了二维索引的错误。
  3. 统一参考线:使用整个数据集的极值绘制y=x参考线,确保所有基因图的基准线范围一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:36:20