I have an Excel report with several tables arranged in the sheet and I'm parsing it with Pandas. The key,value pairs I'm scraping out of the report are always in the same columns. So, I separted my lookups into groups where the key,values are the same, and use iloc to find the correct row:
df[df.iloc[:, key_column] == 'apple'][value_column].values[0]
Many keys are present in every file, but occasionally one is not present. In the rare event of an always-present-key not being present the whole block will fail (index 0 is out of bounds for axis 0 with size 0)
try:
parsed_xls['fruit'] = df[df.iloc[:, key_column] == 'apple'][value_column].values[0]
parsed_xls['vegetable'] = df[df.iloc[:, key_column] == 'onion'][value_column].values[0]
parsed_xls['stationary'] = df[df.iloc[:, key_column] == 'stapler'][value_column].values[0]
except:
# error reporting
Short of putting each key,value pair in it's own try...except, or a helper function to supply zero value when the key search fails...
Is there a more Pandas-like way to handle iloc lookups which raise this exception (and still catch errors)?
key_columnthat may not be present orvalue_column? Or is it just possible that there may not be any such key present in the key column? Which is it?