Pandas DataFrame - Select Columns except specified


Pandas DataFrame - Select columns except specified

To select columns except specified, in Pandas DataFrame, you can use DataFrame.drop() method. Call drop() method on the DataFrame, and pass the columns to be excluded in the resulting DataFrame.

The syntax to select columns expect specified using DataFrame.drop() method is

df.drop(columns=columns_to_exclude)

You have to replace columns_to_exclude with the list of column labels.

For example, if you would like to select columns except column 'B' of a DataFrame df, then use the following expression.

df.drop(columns=['B'])

The method returns a new DataFrame with the specified columns dropped from the original DataFrame. The original DataFrame remains unchanged.

Examples

1. Select columns except column 'B' from DataFrame using drop()

In the following program, we are given a DataFrame in df_input with three columns: A, B, and C. We have to select the columns except for the column B in the given DataFrame using drop() method of the DataFrame.

Steps

  1. Given a DataFrame in df_input with three columns: A, B, and C.
df_input = pd.DataFrame({
    'A': [2, 4, 6, 8, 10],
    'B': [1, 3, 5, 7, 9],
    'C': [5, 10, 15, 20, 25]
})
  1. Call drop() method on the DataFrame df_input and pass the column list with 'B' label in it as argument for the columns parameter.
df_input.drop(columns=['B'])
  1. The method returns a new DataFrame without the specified column. Store the returned DataFrame in df_result.
df_result = df_input.drop(columns=['B'])
  1. You may print the DataFrame df_result to output.
print(df_result)

Program

Complete Python program to select all columns except specified ones in a Pandas DataFrame.

Python Program

import pandas as pd

# Take a DataFrame
df_input = pd.DataFrame({
    'A': [2, 4, 6, 8, 10],
    'B': [1, 3, 5, 7, 9],
    'C': [5, 10, 15, 20, 25]
})

# Select columns except 'B'
df_result = df_input.drop(columns=['B'])
print(df_result)

Output

    A   C
0   2   5
1   4  10
2   6  15
3   8  20
4  10  25

Summary

In this Pandas Tutorial, we learned how to select columns from DataFrame expect specified columns using DataFrame drop() method, with examples.