0
0
Pandasdata~5 mins

Dropping columns and rows in Pandas

Choose your learning style9 modes available
Introduction

Sometimes, data has extra information we don't need. Dropping columns or rows helps us keep only the useful parts.

You want to remove a column with irrelevant data from your table.
You need to delete rows that have missing or wrong information.
You want to simplify your data by keeping only certain columns.
You want to clean your data before analysis by removing unwanted rows or columns.
Syntax
Pandas
DataFrame.drop(labels=None, axis=0, inplace=False)

labels: Name or list of names of rows or columns to drop.

axis=0 means drop rows, axis=1 means drop columns.

Examples
Drop a single column named 'column_name'.
Pandas
df.drop('column_name', axis=1)
Drop multiple rows named 'row1' and 'row2'.
Pandas
df.drop(['row1', 'row2'], axis=0)
Drop a column and change the original DataFrame directly.
Pandas
df.drop('column_name', axis=1, inplace=True)
Sample Program

This code creates a table with names, ages, and cities. Then it shows how to remove the 'City' column and how to remove the row for Bob (index 1).

Pandas
import pandas as pd

# Create a simple DataFrame
data = {'Name': ['Anna', 'Bob', 'Cara'],
        'Age': [25, 30, 22],
        'City': ['NY', 'LA', 'SF']}
df = pd.DataFrame(data)

print('Original DataFrame:')
print(df)

# Drop the 'City' column
df_dropped_col = df.drop('City', axis=1)
print('\nDataFrame after dropping column City:')
print(df_dropped_col)

# Drop the row with index 1 (Bob)
df_dropped_row = df.drop(1, axis=0)
print('\nDataFrame after dropping row with index 1:')
print(df_dropped_row)
OutputSuccess
Important Notes

Using inplace=True changes the original DataFrame without needing to assign it again.

If you try to drop a label that does not exist, pandas will raise an error.

Summary

Use drop() to remove rows or columns from your data.

Set axis=0 to drop rows, axis=1 to drop columns.

Use inplace=True to change the original data directly.