python - 从 URL 到 `pandas.DataFrame` 的 Excel 工作簿表

标签 python url pandas xlrd

在查看了读取 url 链接(指向 .xls 文件)的不同方法后,我决定继续使用 xlrd。

我很难将“xlrd.book.Book”类型转换为“pandas.DataFrame”

我有以下内容:

import pandas
import xlrd 
import urllib2

link ='http://www.econ.yale.edu/~shiller/data/chapt26.xls'
socket = urllib2.urlopen(link)

#this line gets me the excel workbook 
xlfile = xlrd.open_workbook(file_contents = socket.read())

#storing the sheets
sheets = xlfile.sheets()

我想获取最后一张 sheets 并作为 pandas.DataFrame 导入,关于如何实现这一点有什么想法吗?我试过了,pandas.ExcelFile.parse() 但它需要一个 excel 文件的路径。我当然可以将文件保存到内存然后解析(使用 tempfile 或其他东西),但我正在尝试遵循 pythonic 指南并使用 可能 已经写入 pandas 的功能.

一如既往地非常感谢任何指导。

最佳答案

您可以将您的套接字传递给ExcelFile:

>>> import pandas as pd
>>> import urllib2
>>> link = 'http://www.econ.yale.edu/~shiller/data/chapt26.xls'
>>> socket = urllib2.urlopen(link)
>>> xd = pd.ExcelFile(socket)
NOTE *** Ignoring non-worksheet data named u'PDVPlot' (type 0x02 = Chart)
NOTE *** Ignoring non-worksheet data named u'ConsumptionPlot' (type 0x02 = Chart)
>>> xd.sheet_names
[u'Data', u'Consumption', u'Calculations']
>>> df = xd.parse(xd.sheet_names[-1], header=None)
>>> df
                                   0   1   2   3         4
0        Average Real Interest Rate: NaN NaN NaN  1.028826
1    Geometric Average Stock Return: NaN NaN NaN  0.065533
2              exp(geo. Avg. return) NaN NaN NaN  0.067728
3  Geometric Average Dividend Growth NaN NaN NaN  0.012025

关于python - 从 URL 到 `pandas.DataFrame` 的 Excel 工作簿表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15588713/

相关文章:

Python 对象代理 : how to access proxy

python - 运动通知事件未触发

python - python - 如何在python字符串中始终将负零格式化为正零?

linux - 使用curl插入延迟以取消缩短url

python - 如何从包含 DataFrame 的字典创建 DataFrame?

python - 按索引列表进行字符串切片

javascript - 如何将今天的日期插入 URL?

url - Web 服务器日志中包含 'A=0 or ' 0=A 的奇怪 URL

python - 提取另一列中列出的 pandas 中特定列名的值

python - Pandas 在夜间重新采样