我有一个包含多年水数据的csv文件。我将每个水年度分解为自己的数据框。现在,我想对那些水年做一些数学运算,然后将每个水年保存到自己的Excel工作表中。
代码的数学部分正在运行,但是在命名和正确保存循环输出的最后一步时遇到了麻烦。现在,我可以创建excel文件并正确创建工作表名称,但是循环仅将最终迭代保存到所有工作表中。我已经四处搜寻,但无法获得其他类似问题的答案。这是我的第一个python程序,因此请多多指教。
{{1}}
答案 0 :(得分:0)
输入您的代码
writer = pd.ExcelWriter('WFT.xlsx', engine='xlsxwriter')
wyID = [wy2014, wy2015, wy2016, wy2017]
seq = ['wy2014', 'wy2015', 'wy2016', 'wy2017']
for df in wyID: # outer loop that figures out wy20xx
df = df.sort_values(by=['turbidity'], ascending=False)
df['rank'] = df['turbidity'].rank(method = 'first', ascending=0)
df['cunnanes'] = (df['rank'] - 0.4)/(len(df['rank']) + 0.2)*100
for name in seq: # you loop through all the names and write all sheets every time. you want to be writing just one
df.to_excel(writer, sheet_name= name)
writer.save()
代替尝试这个。
for i, df in enumerate(wyID): # outer loop that figures out wy20xx
df = df.sort_values(by=['turbidity'], ascending=False)
df['rank'] = df['turbidity'].rank(method = 'first', ascending=0)
df['cunnanes'] = (df['rank'] - 0.4)/(len(df['rank']) + 0.2)*100
df.to_excel(writer, sheet_name= seq[i]) # writes to correct wy20xx sheet
writer.save() # Now you're done writing the excel