【问题标题】:using Pandas to read in excel file from URL - XLRDError使用 Pandas 从 URL 读取 excel 文件 - XLRDError
【发布时间】:2016-05-15 20:05:48
【问题描述】:

我正在尝试从以下 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 文件。

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

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

【问题讨论】:

    标签: python pandas xlrd


    【解决方案1】:

    看来你可以使用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
    

    【讨论】:

    • 啊,太好了,谢谢!效果很好! - 你只是知道 read_csv 会起作用还是有什么方法可以告诉你?
    • 首先,当我打开带有文件的 url 时,我的 Excel 返回警告。然后我通过Notepad++检查文件,它似乎是csv。所以我使用了 read_csv 并且效果很好。祝你好运!
    • 感谢您的信息 - 我也使用 notepad++ 打开它以尝试查看,但是您在哪里看到它是 csv 的附加信息?我刚刚看到了其中包含的文本数据。
    • 对不起,是txt。没有.csv。但是read_csv 经常读一些结构很好的txt 很不错。感谢您接受。
    【解决方案2】:

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

    • 将 XL 文件上传到 Google 云端硬盘,或使用已上传的文件
    • 通过链接将文件分享给任何人(我不知道仅查看是否有效,但我尝试了完全访问权限)
    • 复制链接

    你会得到这样的东西。

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

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

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

    下载地址: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中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2023-02-10
      相关资源
      最近更新 更多