You need to enable JavaScript to run this app. 使用Pandas遍历行比较数值触发KeyError,如何计算平均葡萄糖变化率?
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas遍历行比较数值触发KeyError,如何计算平均葡萄糖变化率?

报错核心原因
  • 执行dropna剔除空值行后,df1会保留原始数据的行索引,不会自动生成连续的0、1、2…序号。直接用i + 1做索引取值时,会去匹配对应的原索引值,一旦索引出现断档、或遍历到最后一行时i+1超出索引范围,就会触发KeyError: 13的报错。
修复方案
  • 剔除空值后主动重置连续整数索引,用reset_index(drop=True)丢弃无意义的旧索引
  • 调整遍历范围,只遍历到数据集的倒数第二行,从逻辑上避免i+1取到不存在的行
  • 补充峰值匹配后的变化率、葡萄糖利用率计算逻辑,覆盖核心分析需求
修复后可直接运行的完整代码
import pandas as pd

# 读取目标sheet数据
df = pd.read_excel('data.xlsx', sheet_name=1)

# 剔除平均葡萄糖列的空值行,重置为连续索引解决索引断档问题
df1 = df.dropna(subset=["Avg. Glucose (mg/dL)"]).reset_index(drop=True)

peak_result = []

# 遍历到倒数第二行即可,避免i+1越界
for i in range(len(df1) - 1):
    # 仅筛选培养天数大于10的时间节点
    if df1.loc[i, 'Days of Culture'] > 10:
        current_glucose = df1.loc[i, 'Avg. Glucose (mg/dL)']
        next_glucose = df1.loc[i + 1, 'Avg. Glucose (mg/dL)']
        current_day = df1.loc[i, 'Days of Culture']
        next_day = df1.loc[i + 1, 'Days of Culture']

        # 匹配峰值条件:当前值高于相邻下一个时间点的葡萄糖值
        if current_glucose > next_glucose:
            # 计算相邻时间点的葡萄糖变化率(单位:mg/dL/天)
            change_rate = (next_glucose - current_glucose) / (next_day - current_day)
            # 计算相邻区间的葡萄糖消耗(利用率对应消耗差值)
            glucose_util = current_glucose - next_glucose

            peak_result.append({
                "峰值对应培养天数": current_day,
                "峰值葡萄糖浓度(mg/dL)": current_glucose,
                "相邻区间葡萄糖变化率(mg/dL/天)": round(change_rate, 2),
                "区间葡萄糖消耗量(mg/dL)": round(glucose_util, 2)
            })

# 输出检测结果
print("培养10天后检测到的葡萄糖峰值:")
for res in peak_result:
    print(res)
逻辑说明
  • 代码中reset_index(drop=True)的作用是把剔除空值后的行重新从0开始编号,彻底解决索引不连续的问题
  • 用df.loc[i, 列名]的方式取值,比原来的df[列名][i]更稳定,不会因为索引类型问题出现匹配偏差
  • 遍历范围限制在len(df1)-1,不会出现取最后一行时i+1不存在的边界错误
  • 代码直接输出峰值对应的浓度、相邻变化率、葡萄糖消耗值,不需要额外手动计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 01:54:04