How do I drop a column of a pandas dataframe?
- User
How do I drop a column of a pandas dataframe?
Assistant
There are a few different ways to drop a column from a pandas dataframe:
- Using
DataFrame.drop()method:
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) df.drop('B', axis=1)- Using
delstatement:
del df['B']- Assigning back to the dataframe without the column:
df = df.loc[:, df.columns != 'B']- Selecting all columns except the one to drop:
df = df.loc[:, ['A']]So in summary, the main ways are:
df.drop()del df['column']- Reassigning df without the column
- Selecting all columns except the one to drop
This allows you to easily and efficiently drop a single column from a pandas dataframe.
- Using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.