noiivice
noiivice

Reputation: 400

store value in local macro in python

I have a noob question:

sheetlist=['SITC0_Food', 'SITC1_BevTobacco', 'SITC2_Crude', 'SITC3_MineralFuels', 'SITC4_AnimalVegOils', 'SITC5_Chemicals', 'SITC6_Manuf', 'SITC7_Machinery', 'SITC8_Misc', 'SITC9_Commodities', 'All']

for sheet in sheetlist:
    sheet= pd.read_excel('ExportsMatrix.xlsx', sheetname=sheet, skiprows=3)
    sheet.drop(sheet.index[0], inplace=True)

I want to save each sheet as a separate dataframe such that SITC0_Food, SITC1_BevTobacco, etc etc. is one df. The code above saves each sheet in the sheetlist as 'sheet' and overwrites it on each iteration.

What am I doing wrong?

Upvotes: 1

Views: 65

Answers (1)

jezrael
jezrael

Reputation: 862521

You can append to list dfs each sheet:

dfs = []
for sheet in sheetlist:
    sheet= pd.read_excel('ExportsMatrix.xlsx', sheetname=sheet, skiprows=3)
    sheet.drop(sheet.index[0], inplace=True)
    dfs.append(sheet)

    print (dfs[0])

Another solution is use dict for storing DataFrames:

dfs = {}
for sheet in sheetlist:
    df = pd.read_excel('ExportsMatrix.xlsx', sheetname=sheet, skiprows=3)
    df.drop(df.index[0], inplace=True)
    dfs[sheet] = df

    print (dfs['SITC0_Food'])

Upvotes: 1

Related Questions