[英]Python saving data to file/global variable in a loop
I have two for loops in which I call the forecast function. 我有两个for循环,在其中调用了预报功能。 The function returns the forecast value and I want to write it to a file or in a dataframe such that I can save all the predictions and access them outside the loop scope.
该函数返回预测值,我想将其写入文件或数据框中,以便我可以保存所有预测并在循环范围之外访问它们。 I am a little stuck here.
我有点卡在这里。 let me show by example.
让我以身作则。
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')
This is what I want to do but the problem is, well obvious, the data is lost after each iteration. 这是我想要做的,但是问题很明显,每次迭代后数据都会丢失。 Please suggest a way to keep it.
请提出一种保留方法。
To delimit by a tab you can use the sep argument of to_csv: 要用制表符分隔,可以使用to_csv的sep参数:
output.to_csv(file_name, sep='\\t')
output.to_csv(文件名,sep ='\\ t')
To use a specific encoding (eg 'utf-8') use the encoding argument: 要使用特定的编码(例如'utf-8'),请使用encoding参数:
output.to_csv(file_name, sep='\\t', encoding='utf-8')
output.to_csv(文件名,sep ='\\ t',编码='utf-8')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.