From eea9b220cecb23e9927967dfb77ddd6fd45bf5f9 Mon Sep 17 00:00:00 2001 From: FAQ Bot Date: Mon, 19 Oct 2026 03:42:16 +0000 Subject: [PATCH] NEW: How do I avoid `KeyError: 'converted'` when re-running a cell that delet --- ...-keyerror-converted-rerun-delete-target.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 _questions/machine-learning-zoomcamp/misc/042_050caa0da5_avoid-keyerror-converted-rerun-delete-target.md diff --git a/_questions/machine-learning-zoomcamp/misc/042_050caa0da5_avoid-keyerror-converted-rerun-delete-target.md b/_questions/machine-learning-zoomcamp/misc/042_050caa0da5_avoid-keyerror-converted-rerun-delete-target.md new file mode 100644 index 00000000..abd849c6 --- /dev/null +++ b/_questions/machine-learning-zoomcamp/misc/042_050caa0da5_avoid-keyerror-converted-rerun-delete-target.md @@ -0,0 +1,19 @@ +--- +id: 050caa0da5 +question: 'How do I avoid `KeyError: ''converted''` when re-running a cell that deletes + the target column in pandas?' +sort_order: 42 +--- + +This happens because once you run a cell that deletes `converted` (e.g., `del df_train['converted']`), the column is removed from the dataframe. Re-running the same cell tries to delete a column that no longer exists, so pandas raises a `KeyError`. + +A common fix is to make the deletion idempotent by using `drop(..., errors='ignore')`, which won’t crash if the column is already gone: + +```python +# Safe way to remove the target variable on multiple runs +df_train = df_train.drop(columns=['converted'], errors='ignore') +df_val = df_val.drop(columns=['converted'], errors='ignore') +df_test = df_test.drop(columns=['converted'], errors='ignore') +``` + +If you want to avoid rerun issues altogether, you can also structure your preprocessing so the “rename/drop target” step only executes once per notebook run (or reload the original dataframe before re-running. \ No newline at end of file