1

这是一个艰难的过程,但我已经被困了 2 周,如果有人可以帮助我,我将不胜感激。基本上,我有一个电子表格,其中第一行是这样的(我无法在此处粘贴电子表格并以可理解的方式保持其格式):A1=Material, B1=Jan/15, C1=Feb/15 , ..., AW=Dec/18。材料清单(A 列)从 A2 一直到 A6442,每一行都有一个零件编号。从 B2:B6442 开始,每行代表每个零件的数量。因此,B2:AW2 行将是 B1 部分从 jan/15 到 dec/18 的消耗。

考虑到上述情况,我想要做的是遍历每一行,应用 def (triple_exponential_smoothing) 并将系列中的最后 6 个数字返回到 Excel,在单元格 AR 到 AW 上(例如,对于第二行,AR2: AW2)。我将使用前 3.5 年 (B2:AQ2) 作为一年中剩余 6 个月 (AR2:AW2) 的计算基础。当我使用定义的范围(如下所示)运行它时,它可以工作:

series = xw.Range((2,2),(2, 37)).value 

相反,当我运行循环时,我什至无法从函数中获取输出,更不用说将其写回 Excel。到目前为止,我的代码如下:

import os
import xlwings as xw

#Defining folder
os.chdir('G:\...\Reports')

#importing data
wb = xw.Book('sheet.xlsx')
sht = wb.sheets['sheet']
series = [sht.range((i,2),(i, 37)).value for i in range(2, 6443)]

# Holt Winters formula

def initial_trend(series, slen):
     sum = 0.0
     for i in range(slen):
          sum += float(series[i+slen] - series[i]) / slen
    return sum / slen

def initial_seasonal_components(series, slen):
     seasonals = {}
     season_averages = []
    n_seasons = int(len(series)/slen)
    # compute season averages
    for j in range(n_seasons):
         season_averages.append(sum(series[slen*j:slen*j+slen])/float(slen))
# compute initial values
for i in range(slen):
    sum_of_vals_over_avg = 0.0
    for j in range(n_seasons):
        sum_of_vals_over_avg += series[slen*j+i]-season_averages[j]
    seasonals[i] = sum_of_vals_over_avg/n_seasons
return seasonals

def triple_exponential_smoothing(series, slen, alpha, beta, gamma, n_preds):
    result = []
    seasonals = initial_seasonal_components(series, slen)
    for i in range(len(series)+n_preds):
        if i == 0: # initial values
             smooth = series[0]
             trend = initial_trend(series, slen)
             result.append(series[0])
             continue
        if i >= len(series): # we are forecasting
             m = i - len(series) + 1
             result.append((smooth + m*trend) + seasonals[i%slen])
        else:
            val = series[i]
            last_smooth, smooth = smooth, alpha*(val-seasonals[i%slen]) + (1-alpha)*(smooth+trend)
            trend = beta * (smooth-last_smooth) + (1-beta)*trend
            seasonals[i%slen] = gamma*(val-smooth) + (1-gamma)*seasonals[i%slen]
            result.append(smooth+trend+seasonals[i%slen])
    return result

#printing results for the function looped through all rows    

print(triple_exponential_smoothing(series, 12, 0.96970912, 0.07133329, 0, 12))

我错过了什么吗?我愿意接受其他方式,只要我能一次完成所有的行。

谢谢大家。

4

1 回答 1

0

最简单的方法是创建一个在一行上工作的用户定义函数 (UDF),然后您可以根据需要将其复制下来。

For better performance you could read the whole data range into Python, loop through each row, writing the results to a list of lists or a Numpy array, then write all the results back to an Excel range in a single operation. That could also conveniently be written as a UDF.

于 2018-09-11T04:32:51.637 回答