Python读取Excel数据并进行函数拟合

         数据分析过程中,需要对数据趋势进行分析,利用Python进行数据拟合是一种不错的方式,下列以一次、二次、三次函数拟合为例,对下表demo数据进行不同拟合,最终生成函数和曲线。

# -*- coding: utf-8 -*-

import openpyxl
from datashape import string
from openpyxl import load_workbook
import numpy as np
import matplotlib.pyplot as plt

x_data = []
y_data = []
workbook = openpyxl.load_workbook('D:/data/test.xlsx')
sheet = workbook['Sheet1']
for i in range(11):
    x_data.append(sheet.cell(row=(i+2), column=1).value)
    y_data.append(sheet.cell(row=(i+2), column=2).value)
x = np.array(x_data)
y = np.array(y_data)

# 尝试一次函数拟合
parameter = np.polyfit(x, y, 1)  # 1代表一次函数,拟合出的函数被y1调用
y1 = parameter[0] * x + parameter[1]

p = np.poly1d(parameter, variable='x')  # 根据拟合参数,用ploy1d构建函数表达式
print(p)
correction = np.corrcoef(y, y1)[0, 1]  # 用corrcoef方法得出相关系数R,输入R2表示决定系数,用于判断拟合程度
print(correction ** 2)
print(parameter)
plt.plot(x, y, '.')
plt.plot(x, y1)
plt.show()

# 尝试二次函数
parameter = np.polyfit(x, y, 2)
y1 = parameter[0] * x**2 + parameter[1] * x + parameter[2]

p = np.poly1d(parameter, variable='x')  # 根据拟合参数,用ploy1d构建函数表达式
print(p)
correction = np.corrcoef(y, y1)[0, 1]
print(correction ** 2)
print(parameter)
plt.plot(x, y, '.')
plt.plot(x, y1)
plt.show()

# 尝试三次函数
parameter = np.polyfit(x, y, 3)
y1 = parameter[0] * x ** 3 + parameter[1] * x ** 2 + parameter[2] * x + parameter[3]

p = np.poly1d(parameter, variable='x')  # 根据拟合参数,用ploy1d构建函数表达式
print(p)
correction = np.corrcoef(y, y1)[0, 1]
print(correction ** 2)
print(parameter)
plt.plot(x, y, '.')
plt.plot(x, y1)
plt.show()

 

 

Excel数据Demo

x y 0 1000 1 789 2 567 3 230 4 129 5 67 6 88 7 124 8 160 9 233 10 300

 

 

 

  • 7
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值