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

Pandas按日期筛选DataFrame应用自定义函数报索引不存在错误怎么解决

错误原因
  • 核心报错来自.loc的误用:.loc是按**行索引(index)**匹配取值,你传入的items是Date列的字段值,不是行索引的取值,因此无法匹配到对应行,触发报错。
  • 代码存在其他隐性错误:
    1. 函数调用名称不匹配:定义的函数名为optimize,循环调用时写为function(),会触发名称不存在错误。
    2. 列名匹配问题:你描述中日期列名为Date,但代码中取值写为prova.Data.unique(),需先确认列名拼写是否一致。
    3. 索引不匹配问题:np.argmin/np.argmax返回的是子DataFrame的相对位置序号,后续用.loc按行索引取值时,若子DataFrame的行索引不是从0开始的连续整数,会触发二次报错。
    4. 原始列缺失:函数中用到的Margine、Energia_Ingresso_Delta列不在你给出的初始4列清单中,需提前完成这两列的计算。
    5. 浮点数精度问题:while (Energia_In_Eccesso != 0)用浮点数判等会有精度风险,容易触发死循环。
修复方案

方法1:修改原遍历逻辑

import pandas as pd
import numpy as np

# 提前计算需要的Margine、Energia_Ingresso_Delta列,示例如下,可替换为自己的计算逻辑
prova['Margine'] = prova['Energia_Attiva_Uscita_Delta'] - prova['Energia_Attiva_Ingresso_Delta']
prova['Energia_Ingresso_Delta'] = prova['Energia_Attiva_Ingresso_Delta']

def optimize(df):
    # 重置子DataFrame的索引,避免位置索引和行索引不匹配
    df = df.reset_index(drop=True)
    min_index = np.argmin(df.Margine)
    max_index = np.argmax(df.Margine)
 
    Energia_Prelevata_Da_Rete = df[df.Margine < 0]['Margine'].sum().round(1)
    Energia_In_Eccesso = df[df.Margine > 0]['Margine'].sum().round(1)

    # 避免除0错误
    neg_count = df[df['Margine']<0]['Margine'].count()
    if neg_count == 0 or Energia_In_Eccesso <= 0:
        return df
    carico_medio = (Energia_In_Eccesso / neg_count).round(1)

    # 改为大于极小值判断,避免精度问题
    while Energia_In_Eccesso > 1e-3: 
        max_index = np.argmax(df.Energia_Ingresso_Delta)
        df.loc[max_index, 'Energia_Attiva_Ingresso_Delta'] = df.loc[max_index,'Energia_Attiva_Ingresso_Delta'] + carico_medio
        Energia_In_Eccesso = (Energia_In_Eccesso - carico_medio).round(1)
    return df

# 按Date列筛选对应日期的子表,调用函数后合并结果
result_list = []
for date_item in prova['Date'].unique(): 
    # 正确筛选指定日期的子表
    sub_df = prova.loc[prova['Date'] == date_item].copy()
    processed_sub_df = optimize(sub_df)
    result_list.append(processed_sub_df)

# 合并所有日期的处理结果得到最终表
final_df = pd.concat(result_list, ignore_index=True)

方法2:更简洁的groupby实现

不需要手动遍历唯一日期,直接用pandas的groupby按日期分组处理,代码更简洁:

final_df = prova.groupby('Date', group_keys=False).apply(optimize).reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:03