I am trying to drop some rows from my Pandas Dataframe df. It looks like this and has 180 rows and 2745 columns. I want to get rid of those rows which have a curv_typ of PYC_RT and YCIF_RT. I also want to get rid of the geo\time column. I am extracting this data from a CSV File and have to realize that curv_typ,maturity,bonds,geo\time and the characters below it like PYC_RT,Y1,GBAAA,EA are all in one column:
curv_typ,maturity,bonds,geo\time 2015M06D16 2015M06D15 2015M06D11 \
0 PYC_RT,Y1,GBAAA,EA -0.24 -0.24 -0.24
1 PYC_RT,Y1,GBA_AAA,EA -0.02 -0.03 -0.10
2 PYC_RT,Y10,GBAAA,EA 0.94 0.92 0.99
3 PYC_RT,Y10,GBA_AAA,EA 1.67 1.70 1.60
4 PYC_RT,Y11,GBAAA,EA 1.03 1.01 1.09
I decided to try and split this Column and then drop the resulting individual columns, but I am getting the error KeyError: 'curv_typ,maturity,bonds,geo\time' in the last line of the code df_new = pd.DataFrame(df['curv_typ,maturity,bonds,geo\time'].str.split(',').tolist(), df[1:]).stack()
import os
import urllib2
import gzip
import StringIO
import pandas as pd
baseURL = "http://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?file="
filename = "data/irt_euryld_d.tsv.gz"
outFilePath = filename.split('/')[1][:-3]
response = urllib2.urlopen(baseURL + filename)
compressedFile = StringIO.StringIO()
compressedFile.write(response.read())
compressedFile.seek(0)
decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')
with open(outFilePath, 'w') as outfile:
outfile.write(decompressedFile.read())
#Now have to deal with tsv file
import csv
with open(outFilePath,'rb') as tsvin, open('ECB.csv', 'wb') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
writer = csv.writer(csvout)
for data in tsvin:
writer.writerow(data)
csvout = 'C:\Users\Sidney\ECB.csv'
#df = pd.DataFrame.from_csv(csvout)
df = pd.read_csv('C:\Users\Sidney\ECB.csv', delimiter=',', encoding="utf-8-sig")
print df
df_new = pd.DataFrame(df['curv_typ,maturity,bonds,geo\time'].str.split(',').tolist(), df[1:]).stack()
Edit: From reptilicus's Answer I used the code below:
#Now have to deal with tsv file
import csv
outFilePath = filename.split('/')[1][:-3] #As in the code above, just put here for reference
csvout = 'C:\Users\Sidney\ECB.tsv'
outfile = open(csvout, "w")
with open(outFilePath, "rb") as f:
for line in f.read():
line.replace(",", "\t")
outfile.write(line)
outfile.close()
df = pd.DataFrame.from_csv("ECB.tsv", sep="\t", index_col=False)
I still get the same exact output as before.
Thank You
df = pd.DataFrame.from_csv(csvout)instead ofpd.read_csv. I am lost as to how to handle this.geo_timemanually in the CSV File, I now get the errorValueError: Shape of passed values is (4, 180), indices imply (4, 179). Do you know why this might be?