a list of dataframes: index 0 is out of bounds for axis 0 with size 0

Question:

Here is the example code/data I am working with. The issue I am having is that when the dataframe is empty with this condition df[df['item_name'] == 'hp' I would be getting an index 0 is out of bounds for axis 0 with 0 message. What would be the best way to correct this code to ignore the indexerror message?

import pandas as pd
#Creating a set of dataframes
data = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],'item_name': ['hp', 'logitech', 'samsung', 'lg', 'lenovo'],
        'price': [1200, 150, 300, 450, 200]}
df1 = pd.DataFrame(data)

data2 = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],'item_name': ['hp', 'mac', 'fujitsu', 'lg', 'asus'],
        'price': [2200, 200, 300, 450, 200]}
df2 = pd.DataFrame(data2)

data3 = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],'item_name': ['microsoft', 'logitech', 'samsung', 'lg', 'asus'],
        'price': [1500, 100, 200, 350, 400]}
df3 = pd.DataFrame(data3)

#creating a list
test=[df1,df2,df3]

#creating a loop for the list
for df in test:
    idx = df.index.get_loc(df[df['item_name'] == 'hp'].index[0])
    vib = df.iloc[idx - 3: idx + 3]
Asked By: yeppi

||

Answers:

You can ignore the error and move on,
if that fits your use case.

for df in test:
    try:
        idx = df.index.get_loc(df[df['item_name'] == 'hp'].index[0])
        vib = df.iloc[idx - 3: idx + 3]
    except IndexError:
        pass
Answered By: J_H
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.