Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading