- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if a column exists in Pandas?
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
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:
", 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.
- Related Articles
- How To Check Or Find If Value Exists In Another Column?
- Check if a value exists in a column in a MySQL table?
- How do I check to see if a column name exists in a CachedRowSet in JDBC?
- How to check if a variable exists in JavaScript?
- How to check if a file exists in Golang?
- How to check if a file exists in Perl?
- How to check if a MySQL database exists?
- How to check whether a column exists in an R data frame?
- How to check if a key exists in a Python dictionary?
- How to check if a File Type Exists in a Directory?
- How to check if hyperlink exists in a worksheet in Excel?
- How to check if a vector exists in a list in R?
- How to check if a key exists in a map in Golang?
- How to check if a file exists or not in Java?
- How to check if an item exists in a C# array?

Advertisements