How to read excel file by cells and transform it into matrix by python?

Viewed 128

For example,how can I read excel file by cells from A1 to C3 and transform them to matrix of 3*3.

2 Answers

You should save your excel table as CSV (comma separated value) and if you open your csv file in noteped you will see your values in shape like this

1,2,3
4,5,6
7,8,9

then you can use python csv library (https://docs.python.org/3/library/csv.html) to read and parse that information and finally to add it into some matrix. Something like this:

import csv

matrix = []

with open('Book1.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in reader:
        x = []
        for el in row:
            x.append(el)
        matrix.append(x)

print(matrix)

You can use Pandas and xlrd to read from excel and transform it to a list.

import pandas as pd
df = pd.read_excel("name.xls", header=None)
matrix = df.values.tolist()
Related