Accumulate values of "neigborhood" from edgelist with numpy
<p>I have a undirected network where each node can be one of <strong>k</strong> types. For each node <em>i</em>, I need to calculate the number of neighbors that node <em>i</em> has of each type.</p>

<p>Right now I am representing the edges with an edgelist where the columns are indexes of the nodes. The nodes are represented as a <strong>n x k</strong> matrix, where each column represents a node type. If a node is of type <em>k</em> then the <em>k</em>th column's value is 1, 0 otherwise.</p>

<p>Here's my current code, which is correct, but too slow.</p>

<pre><code># example nodes and edges, both typically much longer
nodes = np.array([[0, 0, 1], 
                  [0, 1, 0],                       
                  [1, 0, 0]])
edges = np.array([[0, 1],
                  [1, 2]])

neighbors = np.zeros_like(nodes)

for i, j in edges:
   neighbors[i] += nodes[j]
   neighbors[j] += nodes[i]
</code></pre>

<p>Is there some clever numpy that would allow me to avoid this for loop? If the best way to do this is with an adjacency matrix, that is also acceptable.</p>

<p>You can simply use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html" rel="nofollow"><code>np.add.at</code></a> -</p>

<pre><code>out = np.zeros_like(nodes)
np.add.at(out, edges[:,0],nodes[edges[:,1]])
np.add.at(out, edges[:,1],nodes[edges[:,0]])
</code></pre>

python numpy vectorization graph-algorithm numpy-broadcasting