0
0
PandasHow-ToBeginner · 3 min read

How to Drop Rows by Index in pandas DataFrame

To drop rows by index in pandas, use the drop() method with the index label(s) you want to remove. For example, df.drop(index_label) removes the row with that index. You can drop multiple rows by passing a list of index labels.
📐

Syntax

The basic syntax to drop rows by index in pandas is:

  • df.drop(labels, axis=0, inplace=False)

Where:

  • labels is a single index label or list of labels to drop.
  • axis=0 means drop rows (default).
  • inplace=False returns a new DataFrame without the dropped rows; True modifies the original DataFrame.
python
df.drop(index_label)
df.drop([index_label1, index_label2])
df.drop(index_label, inplace=True)
💻

Example

This example shows how to drop rows by their index labels from a pandas DataFrame.

python
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40]}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd'])

# Drop row with index 'b'
new_df = df.drop('b')

# Drop multiple rows with indexes 'a' and 'd'
new_df_multiple = df.drop(['a', 'd'])

print("Original DataFrame:\n", df)
print("\nDataFrame after dropping index 'b':\n", new_df)
print("\nDataFrame after dropping indexes 'a' and 'd':\n", new_df_multiple)
Output
Original DataFrame: Name Age a Alice 25 b Bob 30 c Charlie 35 d David 40 DataFrame after dropping index 'b': Name Age a Alice 25 c Charlie 35 d David 40 DataFrame after dropping indexes 'a' and 'd': Name Age b Bob 30 c Charlie 35
⚠️

Common Pitfalls

Common mistakes when dropping by index include:

  • Forgetting that drop() returns a new DataFrame by default and does not change the original unless inplace=True is set.
  • Passing index values that do not exist, which raises a KeyError.
  • Confusing axis=0 (rows) with axis=1 (columns).
python
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3]}, index=['x', 'y', 'z'])

# Wrong: This does not change df
 df.drop('x')
print(df)

# Right: Use inplace=True or assign back
 df.drop('x', inplace=True)
print(df)
Output
A x 1 y 2 z 3 A y 2 z 3
📊

Quick Reference

ActionCode ExampleDescription
Drop single indexdf.drop('index_label')Drops one row by index label, returns new DataFrame
Drop multiple indexesdf.drop(['idx1', 'idx2'])Drops multiple rows by index labels
Drop inplacedf.drop('index_label', inplace=True)Drops row and modifies original DataFrame
Drop with errors ignoreddf.drop('missing_label', errors='ignore')Avoids error if index label not found

Key Takeaways

Use df.drop(index_label) to remove rows by index label from a DataFrame.
By default, drop() returns a new DataFrame; use inplace=True to modify the original.
Pass a list of index labels to drop multiple rows at once.
Avoid KeyError by ensuring index labels exist or use errors='ignore'.
axis=0 is for rows; do not confuse with axis=1 which drops columns.