s66*_*666 8 python xlrd pandas
我正在尝试从以下 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'
Run Code Online (Sandbox Code Playgroud)
使用代码:
pd.read_excel(url1)
Run Code Online (Sandbox Code Playgroud)
但是它不起作用,我收到错误:
XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '2000/01/'
Run Code Online (Sandbox Code Playgroud)
在 Google 上搜索后,似乎有时通过 URL 提供的 .xls 文件实际上在幕后以不同的文件格式保存,例如 html 或 xml。
当我手动下载 Excel 文件并使用 Excel 打开它时,出现错误消息:文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非你相信它的来源,否则不要打开它”
当我打开它时,它看起来就像一个普通的 Excel 文件。
我在网上看到一篇文章,建议我在文本编辑器中打开该文件,看看是否有任何关于正确文件格式的附加信息,但使用记事本++打开时我没有看到任何附加信息。
有人可以帮我正确地将这个“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
Run Code Online (Sandbox Code Playgroud)
然后我检查最后一列f是否还有其他值NaN:
print df[df.f.notnull()]
Empty DataFrame
Columns: [a, b, c, d, e, f]
Index: []
Run Code Online (Sandbox Code Playgroud)
所以只有NaN,所以你可以f通过参数过滤最后一列usecols:
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
Run Code Online (Sandbox Code Playgroud)