How to Drop Columns in Pandas (4 Examples)


You can use the drop() function to drop one or more columns from a pandas DataFrame:

#drop one column by name
df.drop('column_name', axis=1, inplace=True)

#drop multiple columns by name
df.drop(['column_name1', 'column_name2'], axis=1, inplace=True)

#drop one column by index
df.drop(df.columns[[0]], axis=1, inplace=True)

#drop multiple columns by index
df.drop(df.columns[[0,2,5]], axis=1, inplace=True)

Note the following:

  • The axis argument specifies whether to drop rows (0) or columns (1).
  • The inplace argument specifies to drop the columns in place without reassigning the DataFrame.

The following examples show how to use this function in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'A': [25, 12, 15, 14, 19, 23, 25, 29],
                   'B': [5, 7, 7, 9, 12, 9, 9, 4],
                   'C': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

	A	B	C
0	25	5	11
1	12	7	8
2	15	7	10
3	14	9	6
4	19	12	6
5	23	9	5
6	25	9	9
7	29	4	12

Example 1: Drop One Column by Name

The following code shows how to drop one column from the DataFrame by name:

#drop column named 'B' from DataFrame
df.drop('B', axis=1, inplace=True) 

#view DataFrame
df

	A	C
0	25	11
1	12	8
2	15	10
3	14	6
4	19	6
5	23	5
6	25	9
7	29	12

Example 2: Drop Multiple Columns by Name

The following code shows how to drop multiple columns by name:

#drop columns 'A' and 'C' from DataFrame
df.drop(['A', 'C'], axis=1, inplace=True) 

#view DataFrame
df

        B
0	5
1	7
2	7
3	9
4	12
5	9
6	9
7	4

Example 3: Drop One Column by Index

The following code shows how to drop one column by index:

#drop first column from DataFrame
df.drop(df.columns[[0]], axis=1, inplace=True) 

#view DataFrame
df

        B	C
0	5	11
1	7	8
2	7	10
3	9	6
4	12	6
5	9	5
6	9	9
7	4	12

Example 4: Drop Multiple Columns by Index

The following code shows how to drop multiple columns by index:

#drop multiple columns from DataFrame
df.drop(df.columns[[0, 1]], axis=1, inplace=True) 

#view DataFrame
df

        C
0	11
1	8
2	10
3	6
4	6
5	5
6	9
7	12

Additional Resources

How to Add Rows to a Pandas DataFrame
How to Add a Numpy Array to a Pandas DataFrame
How to Count Number of Rows in Pandas DataFrame

Leave a Reply

Your email address will not be published.