[英]How to multiprocess multiple excel sheets using pandas read_excel?
[英]How to use pandas read_excel() for excel file with multi sheets?
我有一個包含很多工作表的excel文件。 每張工作表中只有一列,即A列。我計划使用read_excel()
方法讀取excel文件。 上面的代碼是:
import pandas as PD
ExcelFile = "C:\\AAA.xlsx"
SheetNames = ['0', '1', 'S', 'B', 'U']
# There are five sheets in this excel file. Those are the sheet names.
PageTotal = len(SheetNames)
for Page in range(PageTotal):
df = PD.read_excel(ExcelFile, header=None, squeeze = True, parse_cols = "A" ,sheetname=str(SheetNames[Page]))
print df
#do something with df
問題是, for loop
僅運行一次。 通過在for loop
運行第二項,它向我顯示以下錯誤文本:
File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 170, in read_excel
io = ExcelFile(io, engine=engine)
File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 227, in __init__
self.book = xlrd.open_workbook(io)
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 422, in open_workbook
ragged_rows=ragged_rows,
File "C:\Python27\lib\site-packages\xlrd\xlsx.py", line 824, in open_workbook_2007_xml
x12sst.process_stream(zflo, 'SST')
File "C:\Python27\lib\site-packages\xlrd\xlsx.py", line 432, in process_stream_iterparse
for event, elem in ET.iterparse(stream):
File "<string>", line 103, in next
IndexError: pop from empty stack
作為一個初學者,我不知道這個錯誤。 有人可以幫我更正密碼嗎? 謝謝。
更新問題: 如果是因為excel文件包含許多公式編寫器和外部鏈接,那么為什么for loop
仍可以運行其第一項? 困惑。
為什么要使用sheetname=str(SheetNames[Page])
?
如果我正確理解了您的問題,我想您想要的是:
import pandas as PD
excel_file = r"C:\\AAA.xlsx"
sheet_names = ['0', '1', 'S', 'B', 'U']
for sheet_name in sheet_names:
df = pd.read_excel(excel_file, header=None, squeeze=True, parse_cols="A", sheetname=sheet_name)
print(df)
#do something with df
在這里引用答案: 對同一工作簿的多個工作表使用Pandas進行pd.read_excel()
也許您可以嘗試以下方法:
import pandas as pd
xls = pd.ExcelFile("C:\\AAA.xlsx")
dfs = []
for x in ['0', '1', 'S', 'B', 'U'] :
dfs.append(xls.parse(x))
或將此作為命令而不是列表,以便您可以輕松獲取特定的工作表
import pandas as pd
xls = pd.ExcelFile("C:\\AAA.xlsx")
dfs = {}
for x in ['0', '1', 'S', 'B', 'U'] :
dfs[x] = xls.parse(x)
您可以簡單地使用:
df = pd.read_excel("C:\\AAA.xlsx", sheet_name=None)
for key, value in df.items():
................
當您設置“ sheet_name = None”時,熊貓會自動從您的工作簿中讀取所有Excel工作表。 為了遍歷工作表及其內容,您可以遍歷'df.items()'並進行任何必須要做的操作。 在上面的代碼中,“鍵”是工作表名稱,“值”是工作表內的內容。 在您的情況下,無需創建額外的列表對象“ sheet_names”。 希望它能解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.