Skip to main content

Command Palette

Search for a command to run...

Checking if a Pandas DataFrame column exists and dropping it

Published
1 min read
M

Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).

import pandas as pd

def drop_column_if_exists(df, column_name):
    if column_name in df.columns:
        df = df.drop(column_name, axis=1)
        print(f"Column '{column_name}' dropped.")
    else:
        print(f"Column '{column_name}' does not exist.")

# Example usage:
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

print("Before dropping column:")
print(df)

drop_column_if_exists(df, 'A')

print("After dropping column:")
print(df)

Output: