Skip to content

[FAQ] How to avoid KeyError when re-running target deletion cells in Jupyter Notebooks #470

Open

Description

@andrew-chung-au

Course

machine-learning-zoomcamp

Question

How do I avoid getting a KeyError: 'converted' when re-running the cell that deletes the target variable?

Answer

This error happens because Jupyter notebooks execute cells out of order or multiple times. Once you delete the target variable from your training dataframe using del df_train['converted'], the column is permanently removed from df_train. Running that same cell a second time triggers a KeyError because the column no longer exists.

The Fix:
You can use pandas .drop() with errors='ignore' so that re-running the cell won't crash if the column has already been removed:

# 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')

### Checklist

- [x] I have searched existing FAQs and this question is not already answered
- [x] The answer provides accurate, helpful information
- [x] I have included any relevant code examples or links

Activity

  1. github-actions commented on Oct 19, 2026

    @github-actions
    Contributor

    ✅ FAQ NEW proposal created in PR #471

    Please review and approve the changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions