Home > front end >  How to fix Pandas extract data?
How to fix Pandas extract data?

Time:05-28

I use this rule in pandas to find value in dataframe in specific column then return some columns back. If it is fails. I got the error.

unpack = dfzips.loc[dfzips.zip == element, ['city', 'county_name', 'state_name', "state_id"]].values[0]

Error is:

IndexError: index 0 is out of bounds for axis 0 with size 0

How to fit it?

CodePudding user response:

You may need to check if there is at least on row having element value in zip column or not. If there is at least one row that zip columns contains element value, then run your code, else do nothing (e.g. use continue command if you are doing in the loop).

For example,

unpack = []
for element in list_of_element:
    if (dfzips.zip == element).sum() > 0:
        unpack  = [dfzips.loc[dfzips.zip == element, ['city', 'county_name', 'state_name', "state_id"]].values[0]]
    else:
        continue
  • Related