使用 Pandas 从 URL 读入 excel 文件 - XLRDError

using Pandas to read in excel file from URL - XLRDError

我正在尝试从以下 URL 将 excel 文件读入到 Pandas:

url1 = 'https://cib.societegenerale.com/fileadmin/indices_feeds/CTA_Historical.xls'

url2 = 'https://cib.societegenerale.com/fileadmin/indices_feeds/STTI_Historical.xls'

使用代码:

pd.read_excel(url1)

但是它不起作用,我收到错误消息:

XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '2000/01/'

在 Google 上搜索后,似乎有时通过 URL 提供的 .xls 文件实际上在幕后以不同的文件格式保存,例如 html 或 xml。

当我手动下载 excel 文件并使用 Excel 打开它时,我收到一条错误消息:文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非你相信它的来源,否则不要打开它

当我打开它时,它看起来就像一个普通的 excel 文件。

我在网上看到 post 建议我在文本编辑器中打开文件,看看是否有关于正确文件格式的任何附加信息,但打开后我没有看到任何附加信息使用记事本++。

有人可以帮我把这个 "xls" 文件正确读入 pandas DataFramj 吗?

看来你可以使用 read_csv:

import pandas as pd

df = pd.read_csv('https://cib.societegenerale.com/fileadmin/indices_feeds/CTA_Historical.xls',
                 sep='\t',
                 parse_dates=[0],
                 names=['a','b','c','d','e','f'])
print df

然后我检查最后一列 f 是否还有其他值 NaN:

print df[df.f.notnull()]

Empty DataFrame
Columns: [a, b, c, d, e, f]
Index: []

所以只有 NaN,所以你可以通过参数 usecols:

过滤最后一列 f
import pandas as pd

df = pd.read_csv('https://cib.societegenerale.com/fileadmin/indices_feeds/CTA_Historical.xls',
                 sep='\t',
                 parse_dates=[0],
                 names=['a','b','c','d','e','f'],
                 usecols=['a','b','c','d','e'])
print df

如果这对某人有帮助.. 您可以通过 URL 直接读取 Google 驱动器文件到 Excel,无需任何登录要求。我在 Google Colab 中试过它有效。

  • 将 XL 文件上传到 Google 驱动器,或使用已上传的文件
  • 与 Link 的任何人共享文件(我不知道是否只能查看,但我尝试了完全访问权限)
  • 复制Link

你会得到这样的东西。

分享 url: https://drive.google.com/file/d/---some--long--string/view?usp=sharing

通过尝试下载文件获取下载 url(从那里复制 url)

它将是这样的:(它具有与上面相同的 google 文件 ID)

下载url:https://drive.google.com/u/0/uc?id=---some--long--string&export=download

现在转到 Google Colab 并粘贴以下代码:

import pandas as pd

fileurl   = r'https://drive.google.com/file/d/---some--long--string/view?usp=sharing'
filedlurl = r'https://drive.google.com/u/0/uc?id=---some--long--string&export=download'

df = pd.read_excel(filedlurl)
df

就是这样..文件在你的 df 中。