2016-11-27 56 views
2

我正在將多個CSV(通過URL)讀取到多個Pandas DataFrame中,並希望將每個CSV的結果存儲到單獨的Excel工作表(選項卡)中。當我在for循環中保留writer.save()時,我只在單個工作表中獲得最後一個結果。當我將writer.save()移動到for循環之外時,我只在單個工作表中獲得第一個結果。兩者都是錯誤的。從CSV讀取並存儲在Excel選項卡中

import requests 
import pandas as pd 
from pandas import ExcelWriter 

work_statements = { 
'sheet1': 'URL1', 
'sheet2': 'URL2', 
'sheet3': 'URL3' 
} 

for sheet, statement in work_statements.items(): 
    writer = pd.ExcelWriter('B.xlsx', engine='xlsxwriter') 
    r = requests.get(statement) # go to URL 
    df = pd.read_csv(statement) # read from URL 
    df.to_excel(writer, sheet_name= sheet) 
writer.save() 

我怎樣才能在三個單獨的工作表中得到所有三個結果?

回答

2

您正在重新初始化每個循環的對象writer。只需在for之前初始化一次,並在循環後保存一次文檔。此外,在read_csv()行,你應該在請求內容閱讀,而不是URL(即statement)保存在詞典:

writer = pd.ExcelWriter('B.xlsx', engine='xlsxwriter') 

for sheet, statement in work_statements.items(): 
    r = requests.get(statement)     # go to URL 
    df = pd.read_csv(r.content)     # read from URL 
    df.to_excel(writer, sheet_name= sheet) 
writer.save() 
+0

這個工作!謝謝 – user3062459

相關問題