首页 > 解决方案 > 嵌入式 R 尝试除了添加循环

问题描述

作为 python/R 新手,我正在关注下面的博客,并且无法在下面的代码中添加循环语句。目前我能够让代码完全运行,但只为 1 个客户输出季节性标志。我希望它为我所有的客户循环和运行。

datamovesme.com/2018/07/01/seasonality-python-code

##Here comes the R code piece     
     try:
          seasonal = r(''' 
          fit<-tbats(customerTS, seasonal.periods = 12, use.parallel = TRUE)
          fit$seasonal
          ''')
      except: seasonal = 1
      seasonal_output = seasonal_output.append({'customer_id':customerid, 'seasonal': seasonal}, ignore_index=True)
      print(f' {customerid} | {seasonal} ')
print(seasonal_output)
seasonal_output.to_csv(outfile)

我已经尝试了许多代码组合来让它循环,这里列出的太多了。该博客显示了现有的数据框和可供我们使用的时间序列对象。我不确定使用哪一个以及如何将其传递给 R 代码。

谢谢 !

标签: pythonrrpy2

解决方案


博客链接维护问题:

  1. 代码没有按照 Python 语法的要求正确缩进行。这可能是由于网站呈现了空白或制表符,但这对读者来说是一种伤害,因为缺少缩进更改输出。

  2. 代码未能注意到附加数据帧的低效率问题:永远不要在 for 循环中调用 DataFrame.append 或 pd.concat。它导致二次复制。相反,由于季节性是一个值,因此构建一个字典列表,您可以将这些字典列表投射到pd.DataFrame()循环之外的构造函数中。

解决上述问题并运行整个代码块后,您的解决方案应该输出一个跨所有customerids的数据框。

# ... same above assignments ...
outfile = '[put your file path here].csv'
df_list = []

for customerid, dataForCustomer in filledIn.groupby(by=['customer_id']):
    startYear = dataForCustomer.head(1).iloc[0].yr
    startMonth = dataForCustomer.head(1).iloc[0].mnth
    endYear = dataForCustomer.tail(1).iloc[0].yr
    endMonth = dataForCustomer.tail(1).iloc[0].mnth

    #Creating a time series object
    customerTS = stats.ts(dataForCustomer.usage.astype(int),
                          start=base.c(startYear,startMonth),
                          end=base.c(endYear, endMonth), 
                          frequency=12)
    r.assign('customerTS', customerTS)

    ##Here comes the R code piece
    try:
        seasonal = r('''
                        fit<-tbats(customerTS, seasonal.periods = 12, use.parallel = TRUE)
                        fit$seasonal
                     ''')
    except: 
        seasonal = 1

    # APPEND DICTIONARY TO LIST (NOT DATA FRAME)
    df_list.append({'customer_id': customerid, 'seasonal': seasonal})
    print(f' {customerid} | {seasonal} ')

seasonal_output = pd.DataFrame(df_list)
print(seasonal_output)
seasonal_output.to_csv(outfile)

推荐阅读