Check if Column Exists in pandas DataFrame in Python (Example)
In this Python article you’ll learn how to test whether a column name exists in a pandas DataFrame.
The tutorial will contain this information:
Sound good? Let’s just jump right in…
Example Data & Add-On Libraries
First, we have to import the pandas library:
import pandas as pd # Import pandas
Next, we also have to create some data that we can use in the example syntax below:
data = pd.DataFrame({'x1':range(1, 6), # Create example DataFrame 'x2':[1, 1, 1, 1, 1], 'x3':[5, 2, 6, 8, 1]}) print(data) # Print example DataFrame
Have a look at the table that has been returned after executing the previous Python programming code. It illustrates that our example DataFrame is constituted of five rows and three variables called “x1”, “x2”, and “x3”.
Example: Test whether Column Name is Contained in pandas DataFrame
In this section, I’ll explain how to search and find a variable name in a pandas DataFrame.
Have a look at the following Python syntax and its output:
print('x1' in data.columns) # Test for existing column # True
The previous Python code has checked if the variable name x1 exists in our example data, and has returned the logical indicator True. In other words: A column with the name x1 is contained in our data set.
Let’s apply the same type of code to a variable name that is not existing in our data:
print('some_name' in data.columns) # Test for non-existing column # False
As you can see, the Python console has returned the logical indicator False, i.e. the column some_name does not exist in our data.
Video, Further Resources & Summary
For more detailed instructions, have a look at the following video, which I have published on my YouTube channel. I show the examples of this tutorial in the video.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Another helpful source for handling rows and columns of a pandas DataFrame is the following video on the YouTube channel of Corey Schafer. In the video instruction, he shows some basics for dealing with pandas DataFrames and series in Python:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Besides the video, you might read the related articles on this website. You can find a selection of related articles below:
- Introduction to the pandas Library in Python
- Determine if Value Exists in pandas DataFrame in Python
- Python Programming Overview
In summary: In this Python tutorial you have learned how to check whether a variable name exists in a pandas DataFrame. Let me know in the comments section below, in case you have further questions and/or comments.