How to Use Drop Method in Pandas: Syntax and Examples
Use the
drop method in pandas to remove rows or columns from a DataFrame by specifying labels. Set axis=0 to drop rows and axis=1 to drop columns. You can also use inplace=True to modify the DataFrame directly.Syntax
The drop method syntax is:
DataFrame.drop(labels, axis=0, inplace=False, errors='raise')
Explanation:
- labels: Single label or list of labels to drop.
- axis: 0 to drop rows, 1 to drop columns.
- inplace: If
True, modifies the original DataFrame; otherwise returns a new one. - errors: 'raise' to throw error if label not found, 'ignore' to skip.
python
DataFrame.drop(labels, axis=0, inplace=False, errors='raise')
Example
This example shows how to drop a row and a column from a DataFrame using drop.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['NY', 'LA', 'Chicago']} df = pd.DataFrame(data) # Drop row with index 1 (Bob) df_row_dropped = df.drop(1) # Drop column 'City' df_col_dropped = df.drop('City', axis=1) print('Original DataFrame:') print(df) print('\nDataFrame after dropping row with index 1:') print(df_row_dropped) print('\nDataFrame after dropping column City:') print(df_col_dropped)
Output
Original DataFrame:
Name Age City
0 Alice 25 NY
1 Bob 30 LA
2 Charlie 35 Chicago
DataFrame after dropping row with index 1:
Name Age City
0 Alice 25 NY
2 Charlie 35 Chicago
DataFrame after dropping column City:
Name Age
0 Alice 25
1 Bob 30
2 Charlie 35
Common Pitfalls
Common mistakes when using drop include:
- Forgetting to set
axis=1when dropping columns, which defaults to dropping rows. - Not using
inplace=Trueif you want to modify the original DataFrame. - Trying to drop labels that do not exist without setting
errors='ignore', which raises an error.
python
import pandas as pd data = {'A': [1, 2], 'B': [3, 4]} df = pd.DataFrame(data) # Wrong: Trying to drop column 'C' without errors='ignore' (raises error) try: df.drop('C', axis=1) except KeyError as e: print(f'Error: {e}') # Right: Use errors='ignore' to avoid error new_df = df.drop('C', axis=1, errors='ignore') print('\nDataFrame after trying to drop non-existent column C with errors=ignore:') print(new_df)
Output
Error: "['C'] not found in axis"
DataFrame after trying to drop non-existent column C with errors=ignore:
A B
0 1 3
1 2 4
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| labels | Label or list of labels to drop | Required |
| axis | 0 to drop rows, 1 to drop columns | 0 |
| inplace | Modify original DataFrame if True | False |
| errors | 'raise' to throw error, 'ignore' to skip missing labels | 'raise' |
Key Takeaways
Use drop with axis=0 to remove rows and axis=1 to remove columns.
Set inplace=True to change the original DataFrame directly.
Use errors='ignore' to avoid errors when labels are missing.
Always specify labels correctly to avoid unexpected results.
Drop returns a new DataFrame by default unless inplace=True is set.