-1

Example :-

Example_workbook has 20 sheets. I want each of them to get assign as individual dataframe in python.I have tried as below but this would be only helpful to get single sheet at a time. Do anyone know how can we use "Def" function to iterate through sheets and assign each of them as new dataframe.

e.g

df = pd.read_excel("practice1.xlsx",sheet_name=0)
Mohamed Thasin ah
  • 10,754
  • 11
  • 52
  • 111
Jitesh Vacheta
  • 85
  • 1
  • 13

2 Answers2

3

The read_excel method reads all the sheets at once if you set the sheet_name kwarg to be None.

sheets = pd.read_excel("practice1.xlsx",sheet_name=None)  # this is a dict
for sheet_name, df in sheets.items():
    "calculations on the dataframe df"

you can read more info about the sheet_name kwarg here

moshevi
  • 4,999
  • 5
  • 33
  • 50
0

Check this one out - you'll get a dictionary of DataFrames, from which you can access each of the dataframes.

import pandas as pd
d={}    
sheets = ['xxx', 'yyy', 'zzz', 'aaa', 'bbb']

for sheet in sheets:
    d[sheet] = pd.read_excel('practice1.xlsx', sheetname=sheet)

Here's the link to the resource:

Create multiple dataframes in loop

Edit: the answer above is actually better, as you don't have to specify sheet names. 'Sheet_name' didn't work for me, so I came up with this solution and only after I realized that typing 'sheetname' (without '_') does the trick for me.

Piotrek
  • 1,400
  • 9
  • 16