如何遍历pandas dataframe并按温度条件删除指定窗口的异常数据行
核心问题原因
你遇到的KeyError是函数逻辑漏洞导致的,和df.drop的基础用法无关,具体问题点有三个:
- 生成的待删除索引包含当前DataFrame不存在的索引值:你通过
range(cent_index-window, cent_index+window)生成的索引可能出现小于0,或者大于当前DataFrame最大索引的情况,这些索引在当前df中不存在,df.drop默认遇到不存在的索引就会抛出KeyError,这是报错的直接原因。 - 边界场景没有兼容:如果某次循环中df里所有温度值都高于当前遍历的temp,
df.index[df['temp']<=temp]会返回空列表,对空列表取max会直接报错。 - 额外小问题:你代码里的
df_dup = df是引用赋值,并不是生成副本,后续修改df的时候df_dup会同步修改,如果需要保留原始数据要改成df_dup = df.copy()。
修复后的实现
def remove_window(df, intervals, window): # 先做副本,避免修改外部传入的原始df df = df.copy() for temp in intervals: match_index = df.index[df['temp'] <= temp] # 兼容无匹配温度的场景 if len(match_index) == 0: continue cent_index = max(match_index) min_idx = df.index.min() max_idx = df.index.max() # 过滤出合法索引,range左闭右开要包含cent_index+window需把结束值+1 drop_indices = [ i for i in range(cent_index - window, cent_index + window + 1) if min_idx <= i <= max_idx ] # 加errors='ignore'做双重保险,避免异常 df.drop(drop_indices, inplace=True, errors='ignore') df.reset_index(drop=True) return df
调用示例
# 用你提供的测试数据调用 res_df = remove_window(df, temp_intervals, window) print(f"原始长度:{before_length},处理后长度:{len(res_df)}")
内容的提问来源于stack exchange,提问作者brosenheim
相关产品推荐
相关产品推荐

