Home > Software engineering >  how to use element as dataframe name when looping over a list
how to use element as dataframe name when looping over a list

Time:05-20

I need to read data from several sheets in a xlsx file, and save data as a dataframe with the same name as sheet name. Here is the code I use. It can read data from different sheets, however, all dataframes are named as temp. How should I change it. Thanks.

import pandas as pd
sheet_name_list = ['sheet1','sheet2','sheet3']

for temp in sheet_name_list:
    temp = pd.read_excel("data_spreadsheet.xlsx", sheet_name = temp)

CodePudding user response:

You can use dictionary:

pd_dict = {}
for temp in sheet_name_list:
    pd_dict[temp] = pd.read_excel("data_spreadsheet.xlsx", sheet_name=temp)
  • Related