在查看了读取 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/