循环遍历电子表格中的行,运行 函数遍历每一行并将结果输出回同一行的末尾

Looping through rows from a spreadsheet, running a function through each row and outputting the result back to the end of the same row

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

考虑到以上情况,我想做的是遍历每一行,应用 def (triple_exponential_smoothing) 和 return 系列中的最后 6 个数字返回 Excel,在单元格 AR 到 AW 上(例如,对于第 2 行,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))

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

提前谢谢大家。

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

为了获得更好的性能,您可以将整个数据范围读入 Python,遍历每一行,将结果写入列表列表或 Numpy 数组,然后将所有结果写回 Excel 一次操作的范围。这也可以方便地写成 UDF。