Question #334   Submitted by Answiki on 12/31/2020 at 01:47:33 PM UTC

In Python, how to drop a column in a Pandas Dataframe?

Answer   Submitted by Answiki on 12/31/2020 at 02:29:21 PM UTC

In Python, there are several ways to drop a column in a Pandas Dataframe. Let consider the following dataframe as an example:

import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns = ["col1", "col2", "col3"])


Option 1: use pandas.dataframe.drop.

df = df.drop("col2", axis=1)


Option 2: use pandas.dataframe.drop without having to reassign df thanks to the inplace=True option.

df.drop("col2", axis=1, inplace=True)


Option 3: use del.

del df["col2"]

6 events in history
Answer by Answiki on 12/31/2020 at 02:29:21 PM

In Python, there are several ways to drop a column in a Pandas Dataframe. Let consider the following dataframe as an example:

import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns = ["col1", "col2", "col3"])


Option 1: use pandas.dataframe.drop.

df = df.drop("col2", axis=1)


Option 2: use pandas.dataframe.drop without having to reassign df thanks to the inplace=True option.

df.drop("col2", axis=1, inplace=True)


Option 3: use del.

del df["col2"]

Question by Answiki 12/31/2020 at 01:56:09 PM
In Python, how to remove a column in a Pandas Dataframe?
Question by Answiki 12/31/2020 at 01:56:00 PM
In Python, how to delete a column in a Pandas Dataframe?
Answer by Answiki on 12/31/2020 at 01:55:50 PM

In Python, there are several ways to drop a column in a Pandas Dataframe. Let consider the following dataframe as an example:

import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns = ["col1", "col2", "col3"])


Option 1: use pandas.dataframe.drop.

df = df.drop("col2", axis=1)


Option 2: use pandas.dataframe.drop without having to reassign df thanks to the inplace=True option.

df.drop("col2", axis=1, inplace=True)


Option 3: use del.

del df["col2"]

Answer by Answiki on 12/31/2020 at 01:55:44 PM

In Python, there are several ways to drop a column in a Pandas Dataframe. Let consider the following dataframe as an example:

import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns = ["col1", "col2", "col3"])


Option 1: use pandas.dataframe.drop.

df = df.drop("col2", axis=1)


Option 2: use pandas.dataframe.drop without having to reassign df thanks to the inplace=True option.

df.drop("col2", axis=1, inplace=True)


Option 3: use del.

del df["col2"]


Question by Answiki 12/31/2020 at 01:47:33 PM
In Python, how to drop a column in a Pandas Dataframe?
# ID Query URL Count

Icons proudly provided by Friconix.