0
0
PandasHow-ToBeginner · 3 min read

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:

  • labels is the index label or list of labels of rows to drop.
  • axis=0 means rows (default).
  • inplace=False returns a new DataFrame without the rows; True modifies 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 unless inplace=True is set.
  • Using labels that do not exist in the index, which raises a KeyError.
  • Confusing axis=0 (rows) with axis=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

MethodDescriptionExample
drop(labels, axis=0, inplace=False)Drop rows by index labelsdf.drop('a')
drop(labels, axis=0, inplace=True)Drop rows and modify original DataFramedf.drop(['a','b'], inplace=True)
drop(labels, errors='ignore')Avoid error if label not founddf.drop('x', errors='ignore')
Boolean filteringDrop rows by conditiondf = 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.