首页 > 解决方案 > How to name dataframes dynamically in Python?

问题描述

I have an excel file which contains more than 30 sheets. However the operation that I do on each sheet remains the same more or less. But my objective is to create a separate dataframe for each sheet, so that I can refer in the future

This is what I tried but it throws an error

xls = pd.ExcelFile('DC_Measurement.xlsx')
sheets = xls.sheet_names
for s in sheets:
    print(s)
    'df '+ s = pd.read_excel(xls, sheet_name=s)

So, it's like I want 30 dataframes to be created and each dataframe will have the sheet name as the suffix name. I tried using the "+" operator but it didn't help either. It threw an error message as shown below

  SyntaxError: can't assign to operator

How can I create dataframes on the fly and name them ?

标签: pythonpython-3.xpandaslistdataframe

解决方案


You could use something like this:

for s in sheets:
    vars()['df'+ s] = pd.read_excel(xls, sheet_name=s)

推荐阅读