Checking if a Pandas DataFrame column exists and dropping it

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: