Drop Columns By Index
Tags: #pandas #snippet #datacleaning #operations
Description: This notebook shows how to drop columns in Pandas DataFrame by index.
Reference: https://www.statology.org/pandas-drop-column-by-index/
import pandas as pd
# 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
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)
columns_dropped = ""
for column in cols:
columns_dropped = columns_dropped + df.columns[column] + ", "
print("The Columns- " + columns_dropped + "are removed from dataframe")
Last modified 1mo ago