ah bon
ah bon

Reputation: 10051

Iterate sheets and count rows in Pandas/Python

If I have an excel file which have multiple sheets, I would like to print out the numbers of entries (rows) exist, except headers, for in each sheet.

df = pd.ExcelFile('./data.xlsx')
df.sheet_names

Out:

['a', 'b', 'c', ...]

The expected result is like:

a has 10 rows
b has 12 rows
c has 5 rows
...

How can I do that? Thanks.

Upvotes: 1

Views: 1837

Answers (1)

Kavin Dsouza
Kavin Dsouza

Reputation: 989

It's fairly simple.

import pandas as pd

# Using sheet_name=None, will read the excel as a dictionary of dataframes
# with key as sheet_name and value as the sheet_dataframe
df_xlsx = pd.read_excel('data.xlsx', sheet_name=None)

# Loop through the sheets and print the number of rows
for sheet_name in df_xlsx.keys():
    df = df_xlsx[sheet_name]
    print(f"{sheet_name} has {len(df.index)} rows")

Upvotes: 3

Related Questions