To check if a column exists in a Pandas DataFrame, we can take the following 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.
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)
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.