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

PandasServer Side ProgrammingProgramming

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:\n", df)

col = "y"
df1 = df.loc[:, df.columns != col]

print "DataFrame without Column-y: \n", 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
raja
Published on 30-Aug-2021 12:07:00
Advertisements