import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
})
# Print the original DataFrame
print("Original DataFrame:")
print(df)
# Remove the 'Age' column
df = df.drop(columns=['Age'])
# Print the updated DataFrame
print("\nDataFrame After Removing 'Age' Column:")
print(df)
Remember to assign the result back to the DataFrame (or to a new variable) if you want to keep the change. If you just want to remove the column temporarily for a specific operation, you can use the inplace=True
argument to modify the DataFrame in place:
df.drop(columns=['Age'], inplace=True)
You can remove a column from a DataFrame by its index
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
})
# Print the original DataFrame
print("Original DataFrame:")
print(df)
# Index of the column to be removed
column_index = 1
# Get the name of the column at the specified index
column_name = df.columns[column_index]
# Drop the column by its name
df.drop(columns=[column_name], inplace=True)
# Print the updated DataFrame
print("\nDataFrame After Removing Column at Index 1:")
print(df)
Remove multiple columns at once from a DataFrame in Pandas
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago'],
'Country': ['USA', 'USA', 'USA']
})
# Print the original DataFrame
print("Original DataFrame:")
print(df)
# List of columns to be removed
columns_to_remove = ['Age', 'Country']
# Drop the specified columns
df.drop(columns=columns_to_remove, inplace=True)
# Print the updated DataFrame
print("\nDataFrame After Removing Columns:")
print(df)
If you want to remove multiple columns by their indices, you can use the following code:
# List of column indices to be removed
column_indices_to_remove = [1, 3]
# Get the names of the columns at the specified indices
columns_to_remove = df.columns[column_indices_to_remove]
# Drop the specified columns
df.drop(columns=columns_to_remove, inplace=True)