Pandas中遇到KeyError时如何继续执行Lambda函数或for循环
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

