How to Use the Pandas explode() Function

Published on Aug. 22, 2023, 12:16 p.m.

To check if a column exists in a Pandas DataFrame you can use the DataFrame.columns attribute which returns an Index object containing the column names. You can check if a column exists by using the in operator with the Index object. Here’s an example:

import pandas as pd

# create a DataFrame
df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})

# check if 'column1' exists
if 'column1' in df.columns:
    print('column1 exists')
else:
    print('column1 does not exist')

Output:

column1 exists

Alternatively, you can use the DataFrame.has_column() method. Here’s an example:

import pandas as pd

# create a DataFrame
df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})

# check if 'column1' exists
if df.has_column('column1'):
    print('column1 exists')
else:
    print('column1 does not exist')

Output:

column1 exists

Both of these methods return a Boolean value indicating whether the column exists or not.

Tags: