python - Python在循环中将数据保存到文件/全局变量
问题描述
我有两个 for 循环,我在其中调用了预测函数。该函数返回预测值,我想将其写入文件或数据框中,以便我可以保存所有预测并在循环范围之外访问它们。我有点卡在这里。让我举例说明。
for country in df['country'].unique():
for channel in df['channel'].unique():
output = pd.DataFrame(columns=['date', 'country',
'channel_id','value'])
x = df[df['country']==country & df['channel']==channel]
pred = forecast(df)
output = output.append(pred)
output.to_csv('forecast.csv')
这是我想做的,但问题是,很明显,每次迭代后数据都会丢失。请提出一种保存方法。
解决方案
要通过制表符分隔,您可以使用 to_csv 的 sep 参数:
output.to_csv(file_name, sep='\t')
要使用特定编码(例如 'utf-8'),请使用 encoding 参数:
output.to_csv(file_name, sep='\t', encoding='utf-8')
推荐阅读
- google-cloud-platform - gcloud 构建提交挂起
- json - 如何为多类型数组定义json schma
- python - 从同一目录导入文件在一个 python 文件中工作但不是另一个?
- r - ggplot 直方图在布尔值上拆分
- excel - 从 VBA Excel for Mac 和 Windows 在 HTTP Post 中发送数据
- r - 意外的聚类错误(围绕介质进行分区)
- python - 在股票页面中抓取雅虎财经对话
- python - _Scraping_ 使用来自论坛的 Beautiful Soup - 如何刮掉重复多次的表?
- javascript - 尝试在 React Native 上运行 Jest,出现多个错误,最后一个是:TypeError: Cannot read property 'createAnimatedComponent' of undefined
- powershell - 无法在 PoweSshell 中显示 export-csv