我正在使用pandas合并多个excel文件,并在下面收到Traceback错误。我不太了解它,并希望有人能帮助我理解它。该作业仍在完成,但它在控制台中出错。这些文件都是xlsx文件,并已打开并重新保存为xlsx,以验证它不是格式问题。
create
正如我所说的那样,作业完成但是合并文件中的所有列都没有排成一行。有些人从A栏上的另一栏开始,另一栏在E栏上。有人可以告诉我为什么它不会从A栏开始追加它。我的剧本如下:
Traceback (most recent call last):
File "/Users/Documents/Python Scripts/Merge Scan xlsx_copy.py",
line 13, in <module>
df = pd.read_excel(f)
File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/pandas/io/excel.py", line 230, in read_excel
io = ExcelFile(io, engine=engine)
File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/pandas/io/excel.py", line 294, in __init__
self.book = xlrd.open_workbook(self._io)
File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/xlrd/__init__.py", line 162, in open_workbook
ragged_rows=ragged_rows,
File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/xlrd/book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/xlrd/book.py", line 1271, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/xlrd/book.py", line 1265, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF
record; found b'\x15Microso'
答案 0 :(得分:0)
对于第一个问题,我正在从具有各种不同文件格式的目录中读取。因此,它试图读取不是xlsx的文件格式,而这正是回溯错误的来源。一旦我将xlsx文件移动到它自己的目录,错误就消失了。
对于第二个问题,正在使用的文件在第1行以外的行上具有标题。对于这些文件,第1行和第5行的标题位于第6行。删除第1行后,文件能够正确合并。
答案 1 :(得分:0)
这将做你想要的。
import pandas as pd
# filenames
excel_names = ["C:/Users/Excel/Desktop/Test/Book1.xlsx", "C:/Users/Excel/Desktop/Test/Book2.xlsx", "C:/Users/Excel/Desktop/Test/Book3.xlsx"]
# read them in
excels = [pd.ExcelFile(name) for name in excel_names]
# turn them into dataframes
frames = [x.parse(x.sheet_names[0], header=None,index_col=None) for x in excels]
# delete the first row for all frames except the first
# i.e. remove the header row -- assumes it's the first
frames[1:] = [df[1:] for df in frames[1:]]
# concatenate them..
combined = pd.concat(frames)
# write it out
combined.to_excel("c.xlsx", header=False, index=False)
# Results go to the default directory if not assigned somewhere else.
# C:\Users\Excel\.spyder-py3
另外,您可能需要考虑使用下面链接中的AddIn。