python - 嵌入式 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 代码。
谢谢 !
解决方案
博客链接维护问题:
代码没有按照 Python 语法的要求正确缩进行。这可能是由于网站呈现了空白或制表符,但这对读者来说是一种伤害,因为缺少缩进更改输出。
代码未能注意到附加数据帧的低效率问题:永远不要在 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)
推荐阅读
- javascript - Highcharts 绘图之间的交互性 - 寻找代码改进
- python - OpenPyxl当单元格的文本包含斜杠时获取真实的单元格值
- reactjs - 反应上下文提供者未在页面加载/刷新时设置值
- java - 打印出字符串而不是引用
- algorithm - GOOGLE 询问的该算法的伪代码是什么
- javascript - javascript代码不能按预期工作需要一些帮助细节放在正文中
- python - 在坐标系opencv python之间转换坐标
- javascript - 无法从网站多次请求
- java - 骑士在爪哇的岩石之旅
- javascript - 如何在 NextJS 中添加自定义脚本包