首页 > 解决方案 > 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')

这是我想做的,但问题是,很明显,每次迭代后数据都会丢失。请提出一种保存方法。

标签: pythonpandasfileloopsdataframe

解决方案


要通过制表符分隔,您可以使用 to_csv 的 sep 参数:

output.to_csv(file_name, sep='\t')

要使用特定编码(例如 'utf-8'),请使用 encoding 参数:

output.to_csv(file_name, sep='\t', encoding='utf-8')


推荐阅读