In this post we will be creating a Python script that will check if a pandas column exists within a data frame. To do this we will be using the ‘in’ operator which will find out whether a given value is a column heading within our data frame.
See below our data frame for this example, here we have three column headings which are ‘Rank’, ‘Name’ and ‘Platform’.
Rank Name Platform 0 1 Wii Sports Wii 1 2 Super Mario Bros. NES 2 3 Mario Kart Wii Wii 3 4 Wii Sports Resort Wii 4 5 Pokemon Red/Pokemon Blue GB 5 6 Tetris GB 6 7 New Super Mario Bros. DS 7 8 Wii Play Wii 8 9 New Super Mario Bros. Wii Wii 9 10 Duck Hunt NES >>>
To check if a column named ‘Rank’ exists within our pandas data frame we would use the snippet of code below.
import pandas as pd if 'Rank' in df: print("Column Exists")
The above would return ‘Column Exists’ as output.
We can also change this to check whether a column does not exist within a data frame, see the snippet of code below as an example.
import pandas as pd if 'Test' not in df: print("Column Does Not Exist")
The above would return ‘Column Does Not Exist” as output.