Python: write list to csv, transposing the first row into a column
<p>Using python, I have data stored in a list:</p>

<pre><code>a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
</code></pre>

<p>I want to write this list to a csv that looks like the following:</p>

<pre><code>a, 1, 2, 3, 4
b, 5, 6, 7, 8
c, 9, 10, 11, 12
</code></pre>

<p>This is the code I came up with after reading lots of other transposing problems:</p>

<pre><code>length = len(a[0])
with open('test.csv', 'w') as test_file:
    file_writer = csv.writer(test_file)
    for i in range(length):
        file_writer.writerow([x[i] for x in a])
</code></pre>

<p>Which gives me:</p>

<pre><code>a,1,5,9
b,2,6,10
c,3,7,11
</code></pre>

<p>So it transposes the entire list (not to mention that some values even get lose), but as shown above, I only want the first row to be transposed. I just don't know where to even get my hand on.</p>

<p>Thanks to Nf4r, I came up with the following -- may look awkward, but works :-)</p>

<pre><code>a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
f = open('test.csv', 'a')
for header, data in zip(a[0], a[1:]):
    result = "{header}, {data}".format(header = header,
                               data = ', '.join((str(n) for n in data)))
    f.write(result)
    f.write('\n')
f.close()
</code></pre>

<p>You just need to pull the first <em>sublist</em> and <em>zip</em> with the remainder then use <em>writerows</em> after combining into a single list:</p>

<pre><code>a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
import csv

with open('test.csv', 'w') as test_file:
    file_writer = csv.writer(test_file)
    it = iter(a)
    col_1 = next(it)
    file_writer.writerows([a] + b for a,b in zip(col_1, it))
</code></pre>

python csv transpose