0

I have a list that looks like:

[('CarrierDel', '1973.0', '4227.0', '518.0', '2701.0', '3249.0', '7354.0', '980.0', '428.0', '394.0'), ('CarrierID', '9E', 'AA', 'AS', 'B6', 'DL', 'EV', 'F9', 'FL', 'HA'), ('Delays', '3626.0', '8394.0', '1071.0', '3880.0', '5927.0', '13836.0', '1461.0', '1254.0', '303.0')]

where 'CarrierDel', 'CarrierID' and 'Delays' are my headers. I want to write this to a csv file. Is there an equivalent to writerow but for columns? Or is there another way to go about this?

Thanks!

1
  • You could compile the three together making rows instead of columns e.g. change what you supplied to something like [('CarrierDel', 'CarrierID', 'Delays')...] and so on. Something like a matrix transpose. Commented Nov 14, 2013 at 17:00

1 Answer 1

4
import csv
w = csv.writer(open("some_file.txt","w"))
w.writerows(zip(*list_of_cols))

should do it

zip transposes a 2d array(among other things) as seen below

 a = [[1,2,3],[4,5,6],[7,8,9]]
 #transpose a with zip
 print zip(*a)  #prints [(1,4,7),(2,5,8),(3,6,9)]
Sign up to request clarification or add additional context in comments.

3 Comments

So that does work for me. But how come when I use with open(output.csv, 'w') as ouput: it separates each item in the csv file?
Sorry I'll try to clarify. When I use exactly what you gave me, it works np. When I try using with open('output.csv', 'w')... my output looks like "['CarrierDel', 'CarrierID', 'Delays']","['1973.0', '9E', '3626.0']","['4227.0', 'AA', '8394.0']","['518.0', 'AS', '1071.0']","['2701.0', 'B6', '3880.0']","['3249.0', 'DL', '5927.0']","['7354.0', 'EV', '13836.0']","['980.0', 'F9', '1461.0']","['428.0', 'FL', '1254.0']","['394.0', 'HA', '303.0']"
no you need to use the csv module ... or manually manage your array ... you cant just write it to a file ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.