Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:<br>", 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.
Advertisements
