Pandas read_excel: only read first few lines

Code Sample, a copy-pastable example if possible

workbook_dataframe = pd.read_excel(workbook_filename, nrows = 10)

Problem description

Using pandas read_excel on about 100 excel files – some are large – I want to read the first few lines of each (header and first few rows of data).

The above doesn’t work but illustrates the goal (example reading 10 data rows).

Author: Fantashit

2 thoughts on “Pandas read_excel: only read first few lines

  1. You can add one line in your code below where you are reading your file. For example, if you want to read first 10 rows of the file then you can do this.

    workbook_dataframe = pd.read_excel(workbook_filename)
    workbook_dataframe =workbook_dataframe.iloc[:10]

    or even you can simply do this
    workbook_dataframe = pd.read_excel(workbook_filename).iloc[:10]

    so that your data frame now contains only first 10 rows.

  2. To get nrows without reading the entire worksheet:

    workbook = pd.ExcelFile(workbook_filename)
    
    # get the total number of rows (assuming you're dealing with the first sheet)
    rows = workbook.book.sheet_by_index(0).nrows
    
    # define how many rows to read
    nrows = 10
    
    # subtract the number of rows to read from the total number of rows (and another 1 for the header)
    workbook_dataframe = pd.read_excel(workbook, skip_footer = (rows - nrows - 1))
    

Comments are closed.