由于最近参加建模比赛需要用到 python 做一些辅助,因此在这里将数学建模中常用的 pyhton 辅助代码记录一下!
python读取 excel 数据
import xlrd
workBook = xlrd.open_workbook(path)
sheet1 = workBook.sheet_by_index(0)
sheet1= workBook.sheet_by_name('Sheet1')
name = sheet1_content1.name
n_rows = sheet1_content1.nrows
n_cols = sheet1_content1.ncols
row_data = sheet1.row_values(i);
col_data = sheet1.col_values(j);
data = sheet1.cell_value(i, j)
python 向 excel 中写入数据
import openpyxl as op
workbook = op.load_workbook(path)
sheet = workbook["Sheet1"]
sheet.cell( row, col, num)
list_data = [1,2,3,4,5,6,7,8,9]
for i in range(0,len(list_data)):
sheet.cell(1, i+1, list_data[i])
workbook.save(path)
python 画图
import matplotlib.pyplot as plt
plt.figure(figsize=(20,16))
plt.title("title")
x = []
for j in range(0,12):
x.append(j)
y2 = [1,5,8,9,6,3,5,4,1,2,8,5]
y1 = []
for j in range(0,12):
y1.append(j)
plt.plot(x,y1,"b-",linewidth=1, marker = '*',label = 'y1')
plt.plot(x,y2,"r-",linewidth=1, marker = '+',label = 'y2')
plt.legend(loc = 0)
plt.xlabel("x")
plt.ylabel("y")
plt.show()
python 画子图(画多个图到一张纸)
import matplotlib.pyplot as plt
plt.figure(figsize=(20,16))
plt.title("title")
x = []
for j in range(0,12):
x.append(j)
y2 = [1,5,8,9,6,3,5,4,1,2,8,5]
y1 = []
for j in range(0,12):
y1.append(j)
splt.subplot(121)
plt.plot(x,y2,"b-",linewidth=1, marker = '*',label = 'XGBoost')
plt.subplot(122)
plt.plot(x,y1,"r-",linewidth=1, marker = '+',label = 'XGBoost')
plt.legend(loc = 0)
plt.xlabel("x")
plt.ylabel("y")
plt.show()
subpolt(121)表示将图分成1行2列并将下一个图放置于第一个位置。如果为222则表示将图纸分割为 2 行 2 列将图放置于第二个位置。
|