Read Excel Data by Row in Python Pandas – Python Pandas Tutorial

By | August 10, 2022

In this tutorial, we will introduce how to read data from an excel file by row using python pandas package. It is easy to do.

Preliminary

We should import python pandas.

import  pandas  as pd

Then, we can use pandas to read an excel.

We can use pandas read_excel() function to read data. However, these data are not ordered by row.

Python Pandas read_excel() – Reading Excel File for Beginners – Pandas Tutorial

How to read data by row in excel using pandas?

We can use code below to read:

def getRows(excel_file, sheet_name, start_row = 1):
    excel_data = pd.read_excel(excel_file, sheet_name = sheet_name, header=None)
    # print(excel_data)
    size = excel_data.shape
    print(size)
    row_num = size[0]
    datax = []
    for i in range(start_row, row_num):
        data = excel_data.iloc[i].values.tolist()
        datax.append(data)
    return datax

If an excel looks like:

read excel data by row in python pandas

We can read it as follows:

excel_file = r"C:\Users\yuzhilun\Desktop\testsa.xlsx"
sheet_name = "Sheet1"
data = getRows(excel_file, sheet_name)

for row in data:
    print(row)

Run this code, we will see:

(11, 5)
[1, 23, 24, 24, 24]
[1, 23, 25, 25, 25]
[1, 23, 26, 26, 26]
[1, 23, 27, 27, 27]
[1, 23, 28, 28, 28]
[1, 23, 29, 29, 29]
[1, 23, 30, 30, 30]
[1, 23, 31, 31, 31]
[1, 23, 32, 32, 32]
[1, 23, 33, 33, 33]

Leave a Reply