'How can I import several Excel sheets into separate pandas dataframes?

I've reviewed this post: Pandas: Save multiple sheets into separate dataframes, however it doesn't seem to address my problem.

So this creates a dictionary with sheet names as keys, and dataframes as values:

sheets = pd.read_excel('Data Series.xlsx',sheet_name=None)

sheets["CPI"] outputs a dataframe.

What I want to do is assign that to its own dataframe like: df_CPI = sheets["CPI"], however I have about 10 sheets to do so I'd rather run it as a loop if possible. Something like

for sheet,dataframe in sheets.items():
   df_`sheet` = pd.read_excel(xls, sheet)


Solution 1:[1]

To create dynamically variables, you have to use globals() or locals() (which is strongly discouraged). The dict version is better.

sheets = pd.read_excel('Data Series.xlsx',sheet_name=None)
for sheet, dataframe in sheets.items():
   globals()[f'df_{sheet}'] = dataframe

Now you can use df_CPI as a variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien