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

Pandas中遇到KeyError时如何继续执行Lambda函数或for循环

Fixing KeyError in Pandas apply() with Lambda/For Loops

Got it, let's resolve that frustrating KeyError so your code can keep processing dates even when they're missing from df_values. Here are a few practical approaches tailored to your scenario:

1. Check Index Existence First (Simple Lambda)

The easiest fix is to add a quick check in your lambda to see if the date exists in df_values' index before calling .loc[]. If it doesn't, return a default value like NaN (or whatever makes sense for your use case):

import pandas as pd
import numpy as np

# Your sample data
df_dates = pd.Series(['7/1/2021', '8/1/2021', '8/2/2021'])
df_values = pd.Series([1, 2], index=['8/1/2021', '8/2/2021'])

# Modified lambda with existence check
df_test = df_dates.apply(lambda x: df_values.loc[x] if x in df_values.index else np.nan)

This avoids the KeyError entirely by skipping the .loc[] call for missing dates.

2. Use Try-Except for Error Handling

If you prefer explicit error catching (useful if you might run into other edge cases), wrap the .loc[] call in a helper function with a try-except block, then pass that function to apply():

def get_safe_value(date):
    try:
        return df_values.loc[date]
    except KeyError:
        # Return your preferred default value here
        return np.nan

df_test = df_dates.apply(get_safe_value)

This is more flexible—you can add logging or custom logic inside the except block if needed.

3. Reindex for High Efficiency (Best for Large Datasets)

For bigger datasets, apply() can be slow. Instead, use pandas' built-in reindex() method to align df_values directly with your df_dates series. This is the most pandas-idiomatic and performant approach:

df_test = df_values.reindex(df_dates)

reindex() will automatically fill missing dates with NaN (you can change this with the fill_value parameter, e.g., fill_value=0 if you want zeros instead of NaNs).

Why This Works

reindex() creates a new series with the exact index from df_dates, pulling values from df_values where they match, and filling gaps with the default (or your specified) value. No loops or lambda functions needed!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 02:47:48