简体   繁体   English

将压缩的CSV文件转换为数据框

[英]Converting zipped CSV File into Dataframe

I am trying to access the "Yield Curve Data" available on this page . 我正在尝试访问此页面上的“屈服曲线数据”。 The code below does this, but I am then trying to convert the zipped CSV File obtained into a Dataframe. 下面的代码执行此操作,但是我随后尝试将获得的压缩CSV文件转换为数据框。 The code below works upto the part when I want to convert the zipped file into a Dataframe. 当我要将压缩文件转换为数据框时,下面的代码可以正常工作。 I get the Error df = pd.DataFrame.from_csv(zipfile.namelist()) in the line df = pd.DataFrame.from_csv(zipfile.namelist()) . 我在df = pd.DataFrame.from_csv(zipfile.namelist())行中收到错误df = pd.DataFrame.from_csv(zipfile.namelist()) df = pd.DataFrame.from_csv(zipfile.namelist()) I was wondering how to circumvent this issue. 我想知道如何规避这个问题。

import urllib, urllib2
import csv
from StringIO import StringIO
import pandas as pd
import os
from zipfile import ZipFile
from pprint import pprint, pformat

my_url = 'http://www.bankofcanada.ca/stats/results/csv'
data = urllib.urlencode({"lookupPage": "lookup_yield_curve.php",
                         "startRange": "1986-01-01",
                         "searchRange": "all"})
request = urllib2.Request(my_url, data)
result = urllib2.urlopen(request)
zipdata = result.read()
zipfile = ZipFile(StringIO(zipdata))

df = pd.DataFrame.from_csv(zipfile.namelist())
print df

Thank You 谢谢

zipfile.namelist just returns a list of filenames -- it does not actually extract anything ( https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.namelist ). zipfile.namelist仅返回文件名列表-实际上不提取任何内容( https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.namelist )。

This should work: 这应该工作:

df = pd.read_csv(zipfile.open(zipfile.namelist()[0]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM