How to Get Index of Item in Pandas DataFrame | Efficient Data Manipulation

To get the index of an item in a Pandas DataFrame, you can use the index attribute along with boolean indexing to locate the row containing the item. Here’s an example:

import pandas as pd

# Create a sample dataframe
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
        'Age': [25, 30, 35, 40, 45],
        'City': ['NYC', 'LA', 'Chicago', 'Miami', 'Seattle']}
df = pd.DataFrame(data)

# Find the index of the row containing the item 'Bob' in the 'Name' column
index = df[df['Name'] == 'Bob'].index[0]

print(index)  # Output: 1

In this example, we first create a sample DataFrame with three columns ‘Name’, ‘Age’, and ‘City’. We then use boolean indexing to locate the row containing the item ‘Bob’ in the ‘Name’ column. Finally, we use the index attribute to retrieve the index of that row, which in this case is 1.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *