首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python中重新创建调用TREND()的Excel公式?

如何在Python中重新创建调用TREND()的Excel公式?
EN

Stack Overflow用户
提问于 2015-03-06 18:06:19
回答 1查看 1.4K关注 0票数 2

我希望在Python中重新创建Excel的趋势函数,并找到了C#答案(How do I recreate an Excel formula which calls TREND() in C#?)。使用这个,我在Python中重新创建了。我想我会发邮件以防万一对别人有用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-06 18:07:37

Python实现:

代码语言:javascript
复制
def LeastSquaresValueAtX(points, knownX, xBar, x):
    '''
        Gets the value at a given x using the line of best fit
        (least square method) to determine the equation
    '''
    slope = SlopeOfPoints(points, knownX, xBar)
    yIntercept = YInterceptOfPoints(points, xBar, slope)
    return (slope * x) + yIntercept

def SlopeOfPoints(points, knownX, xBar):
    '''
        Gets the slope for a set of points using the formula:
        m=sum(x-avg(x)(y-avg(y))/sum(x-avg(x))**2
    '''
    yBar=dividend=divisor=0.0
    for i in points:
        yBar=yBar+i
    yBar=yBar/5
    for j in points:
        kx = knownX.pop()
        dividend+=((kx-xBar)*(j-yBar))
        divisor+=((kx-xBar)**2)
    return dividend / divisor      

def YInterceptOfPoints(points, xBar, slope):
    '''
        Gets the y-intercept for a set of points using the formula:
        b-avg(y)-m(avg(x))
    '''
    yBar =0.0
    for i in points:
        yBar=yBar+i
    yBar=yBar/5
    return yBar - (slope * xBar)

def test(knownX, t):
    if t==1: return LeastSquaresValueAtX([4,13,10,22,20],[2011,2010,2009,2008,2007],2009,2012)
    if t==2: return LeastSquaresValueAtX([7,20,26,29,23],knownX, 2009,2012)
    if t==3: return LeastSquaresValueAtX([6,5,4,3,7], knownX, 2009,2012)


print test([2011,2010,2009,2008,2007], 1)##26.1
print test([2011,2010,2009,2008,2007], 2)##33.3
print test([2011,2010,2009,2008,2007], 3)##5.0
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28904906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档