1

hi:) im currently working on something using python/ pycharm for which i need to access multiple excel worksheets and use the data stored within them. I managed to access the sheets individually, however, there was a lot of repeated code and in an attempt to reduce redundancy, i tried using a for loop (as all the data that i need from each excel worksheet is found in the same rows and columns). this is the code i used to open each sheet:

data_eu_2016 = 'C:/Users/julia/OneDrive/Documents/python assignment/2016 data -EU values.xlsx'
eu_2016_PM10 = pd.read_excel(data_eu_2016 , sheet_name = 'PM10 ', engine = 'openpyxl', skiprows = 6, usecols = 'A:L')
#print(eu_2016_PM10) -to check that the sheet was accessed
eu_2016_PM25 = pd.read_excel(data_eu_2016 , sheet_name = 'PM2.5', skiprows = 6, usecols = 'A:L')
eu_2016_O3 = pd.read_excel(data_eu_2016 , sheet_name = 'O3 ', skiprows = 6, usecols = 'A:L')
eu_2016_NO2 = pd.read_excel(data_eu_2016 , sheet_name = 'NO2 ', skiprows = 6, usecols = 'A:L')
eu_2016_BaP = pd.read_excel(data_eu_2016 , sheet_name = 'BaP', skiprows = 6, usecols = 'A:L')
eu_2016_SO2 = pd.read_excel(data_eu_2016 , sheet_name = 'SO2 ', skiprows = 6, usecols = 'A:L')

(this code is repeated for a few other excel workbooks too, which is why i really want to remove all these blocks of code)

my question is that im not sure on how to do the for loop in this case. this is what i've tried so far:

for sheet in data_path_eu_2016:
    pd.read_excel(data_path_eu_2016, sheet_name="PM10 ",'PM2.5' , 'O3 ', 'NO2 ', 'BaP' ,'SO2 ', engine='openpyxl', index_col=None, skiprows=6, usecols = "A:L")

wherein i essentially left in a whole line of code that i had used before and inserted all the worksheet names instead of just one, however this doesnt work.

any help would be greatly appreciated!!

1 Answers1

0

Try something like this:

wbks = []
for wb in ["PM10 ",'PM2.5' , 'O3 ', 'NO2 ', 'BaP' ,'SO2 ']:
    wbks.append(eu_2016_PM25 = pd.read_excel(data_eu_2016,sheet_name=wb,skiprows=6, usecols='A:L'))

Also good options suggested here.

Alex
  • 731
  • 1
  • 6
  • 21