使用python读取excel,并进行数组加乘运算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zlyaxixuexi/article/details/88372159

刚才,同学问了我一个问题,关于python进行读操作,数组进行加运算和乘运算的,让我觉得,嗯,我一计算机研究生,python都不会,还怎么混社会。

题目是这样的,一个表里有三个sheet,分别为Matrix1(32)Matrix2(32)Matrix3(23),分别读取,并计算Matrix1+Matrix2的值和Matrix1Matrix3的值。

这里分别涉及到了如何读取excel,如何将excel的数据存放到二维数组中,如何进行数组运算。
代码如下:

# -*- coding: utf-8 -*-
"""
Created on Sat Mar  9 20:30:34 2019

@author: 99389
"""

from openpyxl import load_workbook
import numpy

#加载Homework2.xlsx
wb = load_workbook('Homework2.xlsx') 

#读取workbook中所有表格
sheets = wb.sheetnames
#打印所有表的名字
print(sheets)

#遍历每个sheet的数据
sheet1 = wb[sheets[0]]
sheet2 = wb[sheets[1]]
sheet3 = wb[sheets[2]]

#将sheet1的数据保存到num_list1
num_list1 = numpy.zeros((2,3))
i = 0
j = 0
for row in sheet1.rows:
    j=0
    for cell in row:
        num_list1[i][j] = cell.value
        j+=1
    i+=1
print(num_list1)
#将sheet2的数据保存到num_list2
num_list2 = numpy.zeros((2,3))
i = 0
j = 0
for row in sheet2.rows:
    j=0
    for cell in row:
        num_list2[i][j] = cell.value
        j+=1
    i+=1
print(num_list2)
#将sheet3的数据保存到num_list3
num_list3 = numpy.zeros((3,2))
i = 0
j = 0
for row in sheet3.rows:
    j=0
    for cell in row:
        num_list3[i][j] = cell.value
        j+=1
    i+=1
print(num_list3)


#矩阵相加
num_list4 = numpy.zeros((2,3))
for i in range(2):
    for j in range(1):
       num_list4[i][j]= num_list1[i][j]+num_list2[i][j]
print(num_list4)

#矩阵相乘
num_list5 = numpy.dot(num_list1,num_list3)
print(num_list5)

顺便提一句,如何自定义实现点乘函数呢?

猜你喜欢

转载自blog.csdn.net/zlyaxixuexi/article/details/88372159
今日推荐