Home > Software design >  Pandas read_excel - How to try two different sheet names to import
Pandas read_excel - How to try two different sheet names to import

Time:08-04

I am attempting to import a large group of excels and the code that selects what to import is included below.

df = pd.read_excel (file, sheet_name = ['Sheet1', 'Sheet2'])

I know that the excels either use sheet1 or sheet2, however they do not use both. This makes my code error out. Is there anyway to tell pandas to try importing sheet1, and if that errors, trying sheet2?

Thanks for any help.

CodePudding user response:

try:
   df = pd.read_excel (file, sheet_name = ['Sheet1'])
except:
   df = pd.read_excel (file, sheet_name = ['Sheet2'])

CodePudding user response:

Assuming your Excel files aren't too large to import everything, you could do this:

df = pd.read_excel(file, sheet_name=None)

That would return all the sheets in the file as a dict, where the key is sheet name and the value is the dataframe. You can then test for the key you want and use that sheet, and drop the rest.

(Edit: I'll note that this may be a heavy-handed approach, but I tried to generalize the answer to how to select one or more sheets when you aren't sure of their names)

  • Related