How to create an adjacency list from an edge list efficiently
<p>I have a csv that looks like</p>

<pre><code>id1,id2
a,b
c,d
a,e
c,f
c,g
</code></pre>

<p>I read it in  to a dataframe with df = pd.read_csv("file.csv").</p>

<p>I would like to convert it to an adjacency list. That is the output should be</p>

<pre><code>a,b,e
c,d,f,g
</code></pre>

<p>I feel that df.groupby('id1') should help but variable length rows aren't suited to pandas so I am a little stuck. As my csv is large I am looking for an efficient solution however.</p>

<p>What is a good way to do this?</p>

<p>You can indeed <code>groupby</code>, then <code>apply</code> <code>list</code>:</p>

<pre><code>In [48]: df = pd.DataFrame({'id1': ['a', 'c', 'a', 'c', 'c'], 'id2': ['b', 'd', 'e', 'f', 'g']})

In [49]: df.id2.groupby(df.id1).apply(list)
Out[49]: 
id1
a       [b, e]
c    [d, f, g]
Name: id2, dtype: object
</code></pre>

<p>To write it to a CSV file, you can use</p>

<pre><code>df1 = df.id2.groupby(df.id1).apply(list).apply(lambda l: ','.join(l)).reset_index()

df1.id1.str.cat(df1.id2, sep=',').to_csv('stuff.csv', index=False)
</code></pre>

python pandas graph