How to Drop Columns in Pandas

Published on Aug. 22, 2023, 12:16 p.m.

To drop a column in a Pandas DataFrame, you can use the drop() method. Here’s an example:

import pandas as pd

# create a dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# drop column 'B' from the dataframe
df = df.drop('B', axis=1)

# print the resulting dataframe
print(df)

In this example, we first create a Pandas DataFrame with three columns (‘A’, ‘B’, and ‘C’) and three rows. We then use the drop() method to remove the ‘B’ column from the dataframe. The axis=1 argument specifies that we want to drop the column axis, rather than the row axis. Finally, we print out the resulting dataframe to confirm that the column has been dropped.

Note that the drop() method returns a new DataFrame with the specified column removed - if you want to modify the original dataframe in place, you can use the inplace=True argument:

# drop column 'B' from the dataframe in place
df.drop('B', axis=1, inplace=True)

# print the resulting dataframe
print(df)

This code will have the same effect as the previous example, but the original dataframe will be modified rather than creating a new one.

Tags: