0

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)

1 Answer 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. One follow up that I have, is would there be a "better" way to do this? The names of the df's don't need to correspond to the sheets exactly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.