Links

Drop Columns By Index

Tags: #pandas #snippet #datacleaning #operations
Author: Sunny Chugh
Description: This notebook shows how to drop columns in Pandas DataFrame by index.
Reference: https://www.statology.org/pandas-drop-column-by-index/

Input

Import libraries

import pandas as pd

Setup DataFrame

# create DataFrame
df = pd.DataFrame(
{
"team": ["Mavs", "Lakers", "Spurs", "Cavs"],
"first": ["Dirk", "Kobe", "Tim", "Lebron"],
"last": ["Nowitzki", "Bryant", "Duncan", "James"],
"points": [26, 31, 22, 29],
}
)
df

Model

Method : Use drop

The following code shows how to use the drop() function to drop the multiple columns of the pandas DataFrame by index.
# Copy init dataframe
df1 = df.copy()
cols = [0, 1, 3]
df1.drop(df1.columns[cols], axis=1, inplace=True)
print(df1)

Output

Display result

columns_dropped = ""
for column in cols:
columns_dropped = columns_dropped + df.columns[column] + ", "
print("The Columns- " + columns_dropped + "are removed from dataframe")