Python merge list concating unique values as comma seperated
<p>I am trying to get this to work. </p>

<p>Here is my data:</p>

<p>data.csv</p>

<pre><code>id,fname,lname,education,gradyear,attributes
1,john,smith,mit,2003,qa
1,john,smith,harvard,207,admin
1,john,smith,ft,212,master
2,john,doe,htw,2000,dev
</code></pre>

<p>Trying to use this code. Found this code on the Internet, don't fully understand it.</p>

<pre><code>from itertools import groupby
import csv
import pprint


t = csv.reader(open('data.csv'))
t = list(t)


def join_rows(rows):
    def join_tuple(tup):
        for x in tup:
            if x: 
                return x
        else:
            return x
    return [join_tuple(x) for x in zip(*rows)]



for name, rows in groupby(sorted(t), lambda x:x[0]):
    print join_rows(rows)
</code></pre>

<p>However, it does not merge unique values as comma separated.</p>

<p>The output is:</p>

<pre><code>['1', 'john', 'smith', 'ft', '212', 'master']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
</code></pre>

<p>How can I make it like:</p>

<pre><code>['1', 'john', 'smith', 'mit,harvard,ft', '2003,207,212', 'qa,admin,master']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
</code></pre>

<p>If there are more entries for the same column, it should also work. Should not be limited to 3 rows.</p>

<p>Grrrrr .... anybody have tips or ideas?</p>

<p>Thanks in advance!</p>

<p>You can change the definition of <code>join_rows</code> to</p>

<pre><code>import itertools

def join_rows(rows):
    return [(e[0] if i &lt; 3 else ','.join(e)) for (i, e) in enumerate(zip(*rows))]
</code></pre>

<p>What this does is to zip all entries belonging to the same id into tuples. For the first 3 tuples, the first item is returned; for the latter, they are joined by commas.</p>

<pre><code>['1', 'john', 'smith', 'ft,harvard,mit', '212,207,2003', 'master,admin,qa']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
</code></pre>

python