Pandas Dataframe provides a convenient way to store and manipulate tabular data. The index is an important part of a Pandas DataFrame, as it provides a way to uniquely identify each row.

In this article, we will discuss how to check if a value exists in a Pandas DataFrame index.

Index in pandas Dataframe

The index is a label column that serves as a unique identifier for each row in a Pandas DataFrame. The index can be set when a DataFrame is created, or it can be added later with the set index() method. If no index is specified, Pandas will generate one starting at 0.

The following example shows how to create a Dataframe with custom index

import pandas as pd

data = {'Name': ['Johny', 'Mario', 'Bobby', 'Ali'],
        'Age': [26, 31, 39, 44]}

df = pd.DataFrame(data, index=['ID1', 'ID2', 'ID3', 'ID4'])

After creating the DataFrame with a custom index using the index parameter, the DataFrame looks like below:

     Name  Age
ID1  Johny  25
ID2  Mario  30
ID3  Bobby  35
ID4  Ali    40

Check if value exist in DataFrame index

To check if a value exists in the index of a Pandas DataFrame, we can use the in operator. The in operator returns True if the value is found in the index, and returns the False if the value is not present in the index.

Following example shows how to check if the value present in the Dataframe index or not:

if 'ID2' in df.index:
    print('ID2 exists in the index')
else:
    print('ID2 does not exist in the index')

In this example, we check if the value ‘ID2‘ exists in the DataFrame df’s index. The in operator is used to determine whether the value exists in the index. If the value is found, the message ‘ID2 exists in the index‘ is displayed. If the value is not found, the message ‘ID2 does not exist in the index‘ is displayed.

Categorized in:

Tagged in: