user131983
user131983

Reputation: 3927

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

Upvotes: 2

Views: 1015

Answers (1)

Brett Patterson
Brett Patterson

Reputation: 226

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]))

Upvotes: 5

Related Questions