【发布时间】:2022-02-03 04:35:41
【问题描述】:
我正在尝试将xls 文件(只有一个选项卡)打开到 pandas 数据框中。
这是一个我通常可以在 excel 或 excel for web 中读取的文件,实际上这是原始文件本身:https://www.dropbox.com/scl/fi/zbxg8ymjp8zxo6k4an4dj/product-screener.xls?dl=0&rlkey=3aw7whab78jeexbdkthkjzkmu。
我注意到前两行合并了单元格,一些列也是如此。
我尝试了几种方法(从堆栈中),但都失败了。
# method 1 - read excel
file = "C:\\Users\\admin\\Downloads\\product-screener.xls"
df = pd.read_excel(file)
print(df)
错误:Excel file format cannot be determined, you must specify an engine manually.
# method 2 - pip install xlrd and use engine
file = "C:\\Users\\admin\\Downloads\\product-screener.xls"
df = pd.read_excel(file, engine='xlrd')
print(df)
错误:Unsupported format, or corrupt file: Expected BOF record; found b'\xef\xbb\xbf<?xml'
# method 3 - rename to xlsx and open with openpyxl
file = "C:\\Users\\admin\\Downloads\\product-screener.xlsx"
df = pd.read_excel(file, engine='openpyxl')
print(df)
错误:File is not a zip file
(可能转换,而不是重命名,是一种选择)。
# method 4 - use read_xml
file = "C:\\Users\\admin\\Downloads\\product-screener.xls"
df = pd.read_xml(file)
print(df)
此方法实际上会产生一个结果,但会产生一个与工作表无关的 DataFrame。大概需要解释 xml(似乎很复杂)?
Style Name Table
0 NaN None NaN
1 NaN All funds NaN
# method 5 - use read_table
file = "C:\\Users\\admin\\Downloads\\product-screener.xls"
df = pd.read_table(file)
print(df)
此方法将文件读入一列(系列)DataFrame。那么如何使用这些信息来创建与 xls 文件形状相同的标准 2d DataFrame 呢?
0 <Workbook xmlns="urn:schemas-microsoft-com:off...
1 <Styles>
2 <Style ss:ID="Default">
3 <Alignment Horizontal="Left"/>
4 </Style>
... ...
226532 </Cell>
226533 </Row>
226534 </Table>
226535 </Worksheet>
226536 </Workbook>
# method 5 - use read_html
file = "C:\\Users\\admin\\Downloads\\product-screener.xls"
df = pd.read_html(file)
print(df)
这会返回一个空白列表[],而人们可能期望至少有一个 DataFrame 列表。
所以问题是将这个文件读入数据框(或类似的可用格式)的最简单方法是什么?
【问题讨论】:
-
文件链接(在谷歌文档上)也在这里:docs.google.com/spreadsheets/d/…
-
您的
"xls"文件实际上是一个xml Spreadsheet文件(只需使用例如记事本查看)。 Pandas/openpyxl 无法读取这种电子表格文件。您可以尝试this solution 作为解决方法(虽然我没有测试它)。 -
这似乎是一个更接近的解决方案(因此赞成),但尚未完成。现在将一小部分(从第 800 行到第 870 行)但不是全部的数据解析到 DataFrame 中。标题也丢失了。那么问题来了,如何用方法捕获所有的数据呢?
标签: python python-3.x excel pandas dataframe