[英]Python Pandas. Loop through Excel Worksheets and clean before concatenate
[英]How to loop through multiple excel worksheets and sort data using python?
從網上下載電子表格后,需要使用python 2.7對5個工作表中的4個進行排序。 我已經能夠拼湊代碼以下載和保存文件,然后對其進行排序。 但是,我已經能夠弄清楚如何遍歷多個工作表。
碼
import os
import os.path
import urllib
import xlwt
from xlrd import open_workbook
destination = 'C:\Users\Python'
if os.path.exists(destination) is False:
os.mkdir(destination)
urllib.urlretrieve("http://www.eia.gov/dnav/pet/xls/PET_PRI_FUT_S1_D.xls", os.path.join(destination, "test.xls"))
target_column = 0
book = open_workbook('test.xls')
sheet = book.sheets()[1]
data = [sheet.row_values(i) for i in xrange(sheet.nrows)]
labels = data[0] # Don't sort our headers
data = data[1:] # Data begins on the second row
data.sort(key=lambda x: x[target_column], reverse=True)
bk = xlwt.Workbook()
sheet = bk.add_sheet(sheet.name)
for idx, label in enumerate(labels):
sheet.write(0, idx, label)
for idx_r, row in enumerate(data):
for idx_c, value in enumerate(row):
sheet.write(idx_r+1, idx_c, value)
bk.save('result.xls')
您可以遍歷工作表,而不用抓一張紙。
for sheet in book.sheets():
代替
sheet = book.sheets()[1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.