Test whether Column Name Exists in pandas DataFrame in Python (Example Code)
In this post, I’ll explain how to test whether a column name exists in a pandas DataFrame in the Python programming language.
Setting up the Example
import pandas as pd # Load pandas library |
import pandas as pd # Load pandas library
my_df = pd.DataFrame({'A':[5, 7, 1, 2, 8, 2], # Construct example DataFrame in Python 'B':[1, 2, 3, 4, 5, 6]}) print(my_df) # Display example DataFrame in console # A B # 0 5 1 # 1 7 2 # 2 1 3 # 3 2 4 # 4 8 5 # 5 2 6 |
my_df = pd.DataFrame({'A':[5, 7, 1, 2, 8, 2], # Construct example DataFrame in Python 'B':[1, 2, 3, 4, 5, 6]}) print(my_df) # Display example DataFrame in console # A B # 0 5 1 # 1 7 2 # 2 1 3 # 3 2 4 # 4 8 5 # 5 2 6
Example: Searching for Column Name in pandas DataFrame
print('B' in my_df.columns) # Test for existing column # True |
print('B' in my_df.columns) # Test for existing column # True