Reputation: 319
It seems like a simple question but I can't figure it out from googling and reading through Stackoverflow.
My question is how can I use a try statement on a variable and append it to a list?
In the sample below, I'm trying to obtain index labels using pandas from a list of files. I want to convert each one into a variable, append them all into a list and concatenate them. However I'm struggling to understand how I can try "parsed_file.loc["Staff" : "Total Staff"].copy()", and convert it into a variable to be appended to a list.
I sort of understand that in the example below I'm trying to use a local scope variable in global scope which would throw a NameError. I could use a function and return the variable within the function, but I then get a 'TypeError: cannot concatenate a non-NDFrame object'. I tried to convert the variable into a DataFrame in the function but it returns the same error.
Not all files will have the index label, therefore I'm using the except: KeyError to skip those files, and print the file location.
for file_ in allFiles:
parsed_file = read_workbook(file_)
parsed_file['filename'] = os.path.basename(file_)
parsed_file.set_index(0, inplace = True)
parsed_file.index.str.strip()
try: Staff_ = parsed_file.loc["Staff" : "Total Staff"].copy()
except KeyError:
print(file_)
list_.append(Staff_)
frame = pd.concat(list_)
Upvotes: 0
Views: 6409
Reputation: 7630
Everything inside an try block will execute line by line and if an exception occures it will stop execution and jump to the except block. So I have changed your code a bit and if there is an exception on the line where you execute Staff_ = parsed_file.loc["Staff" : "Total Staff"].copy()
it wont execute the rest of the lines within the try block. Documentation here describes try Python Try Catch
for file_ in allFiles:
parsed_file = read_workbook(file_)
parsed_file['filename'] = os.path.basename(file_)
parsed_file.set_index(0, inplace = True)
parsed_file.index.str.strip()
try:
Staff_ = parsed_file.loc["Staff" : "Total Staff"].copy()
# Line below won't be executed in case of an exception
list_.append(Staff_)
except KeyError:
print(file_)
frame = pd.concat(list_)
Upvotes: 1