简体   繁体   中英

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. 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()) . 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 ).

This should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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