How to check if a column exists in Pandas?

PandasServer Side ProgrammingProgramming

To check if a column exists in a Pandas DataFrame, we can take the following Steps −

Steps

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

  • Print the input DataFrame, df.

  • Initialize a col variable with column name.

  • Create a user-defined function check() to check if a column exists in the DataFrame.

  • Call check() method with valid column name.

  • Call check() method with invalid column name.

Example

 Live Demo

import pandas as pd

def check(col):
   if col in df:
      print "Column", col, "exists in the DataFrame."
   else:
      print "Column", col, "does not exist in the DataFrame."

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 = "x"
check(col)
col = "a"
check(col)

Output

Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0
Column x exists in the DataFrame.
Column a does not exist in the DataFrame.
raja
Published on 30-Aug-2021 12:10:22
Advertisements