How to select all columns except one in a Pandas DataFrame?



To select all columns except one column in Pandas DataFrame, we can use df.loc[:, df.columns != <column name>].

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame, df.

  • Initialize a variable col with column name that you want to exclude.

  • Use df.loc[:, df.columns != col] to create another DataFrame excluding a particular column.

  • Print the DataFrame without col column.

Example

 Live Demo

import pandas as pd df = pd.DataFrame(    {       "x": [5, 2, 1, 9],       "y": [4, 1, 5, 10],       "z": [4, 1, 5, 0]    } ) print("Input DataFrame is:
"
, df) col = "y" df1 = df.loc[:, df.columns != col] print "DataFrame without Column-y:
"
, df1

Output

Input DataFrame is:    x  y  z 0  5  4  4 1  2  1  1 2  1  5  5 3  9 10  0 DataFrame without Column-y:    x  z 0  5  4 1  2  1 2  1  5 3  9  0
Updated on: 2023-09-13T15:54:47+05:30

35K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements