How to Drop Row in pandas: Simple Guide with Examples
To drop a row in pandas, use the
DataFrame.drop() method with the row's index label or labels. You can also drop rows based on a condition by filtering the DataFrame.Syntax
The basic syntax to drop rows by index is:
DataFrame.drop(labels, axis=0, inplace=False)
Where:
labelsis the index label or list of labels of rows to drop.axis=0means rows (default).inplace=Falsereturns a new DataFrame without the rows;Truemodifies the original DataFrame.
python
df.drop(labels, axis=0, inplace=False)
Example
This example shows how to drop a single row by index label and multiple rows by a list of labels.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 35, 40]} df = pd.DataFrame(data, index=['a', 'b', 'c', 'd']) # Drop single row with index 'b' df_single_drop = df.drop('b') # Drop multiple rows with indexes 'a' and 'd' df_multiple_drop = df.drop(['a', 'd']) print('Original DataFrame:\n', df) print('\nAfter dropping row with index b:\n', df_single_drop) print('\nAfter dropping rows with indexes a and d:\n', df_multiple_drop)
Output
Original DataFrame:
Name Age
a Alice 25
b Bob 30
c Charlie 35
d David 40
After dropping row with index b:
Name Age
a Alice 25
c Charlie 35
d David 40
After dropping rows with indexes a and d:
Name Age
b Bob 30
c Charlie 35
Common Pitfalls
Common mistakes when dropping rows include:
- Forgetting that
drop()returns a new DataFrame by default and does not change the original unlessinplace=Trueis set. - Using labels that do not exist in the index, which raises a
KeyError. - Confusing
axis=0(rows) withaxis=1(columns).
python
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data, index=['a', 'b']) # Wrong: trying to drop a non-existing index 'c' (raises KeyError) # df.drop('c') # Correct: use errors='ignore' to avoid error new_df = df.drop('c', errors='ignore') # Wrong: forgetting inplace=True means original df is unchanged # df.drop('a') # Correct: modify original df df.drop('a', inplace=True) print(new_df) print(df)
Output
Name Age
a Alice 25
b Bob 30
Name Age
b Bob 30
Quick Reference
| Method | Description | Example |
|---|---|---|
| drop(labels, axis=0, inplace=False) | Drop rows by index labels | df.drop('a') |
| drop(labels, axis=0, inplace=True) | Drop rows and modify original DataFrame | df.drop(['a','b'], inplace=True) |
| drop(labels, errors='ignore') | Avoid error if label not found | df.drop('x', errors='ignore') |
| Boolean filtering | Drop rows by condition | df = df[df['Age'] > 30] |
Key Takeaways
Use df.drop() with row index labels to remove rows from a DataFrame.
Set inplace=True to modify the original DataFrame directly.
Use errors='ignore' to avoid errors when labels do not exist.
You can also drop rows by filtering with conditions instead of drop().
Remember axis=0 means rows; axis=1 means columns.