I have an input csv that look like
email,trait1,trait2,trait3
foo@gmail,biz,baz,buzz
bar@gmail,bizzy,bazzy,buzzy
foobars@gmail,bizziest,bazziest,buzziest
and I need the output format to look like
Indv,AttrName,AttrValue,Start,End
foo@gmail,"trait1",biz,,,
foo@gmail,"trait2",baz,baz,,
foo@gmail,"trait3",buzz,,,
For each row in my input file I need to write a row for the N-1 columns in the input csv. The Start and End fields in the output file can be empty in some cases.
I'm trying to read in the data using a DictReader. So for i've been able to read in the data with
import unicodecsv
import os
import codecs
with open('test.csv') as csvfile:
reader = unicodecsv.csv.DictReader(csvfile)
outfile = codecs.open("test-write", "w", "utf-8")
outfile.write("Indv", "ATTR", "Value", "Start","End\n")
for row in reader:
outfile.write([row['email'],"trait1",row['trait1'],'',''])
outfile.write([row['email'],"trait2",row['trait2'],row['trait2'],''])
outfile.write([row['email'],"trait3",row['trait3'],'','')
Which doesn't work. (I think I need to cast the list to a string), and is also very brittle as I'm hardcoding the column names for each row. The bigger issue is that the data within the for loop isn't written to "test-write". Only the line
outfile.write("Indv", "ATTR", "Value", "Start","End\n") actually write out to the file. Is DictReader the appropriate class to use in my case?
codecs.open('test-write', 'w', 'utf-8')be identical toopen('test-write', 'uw')? Similarly can't you opentest.csvasurand use the normalcsvmodule? Maybe I'm oversimplifying thoughStartandEndcolumns refer to. ButPandasmay have a solution for you. I get so far without further understanding what you want:import pandas as pdpd1 = pd.read_csv('input_csv.csv').stack()This gets a similar looking form, which after filling out what theStartandEndmean, can be written to csv usingpd1.to_csv().