Calculate average neighbor degree in networkX according to the attributes of the neighboring nodes

Viewed 1236

In my graph, the nodes have an attribute that tells me the type of node can be 1 or 2.

G=nx.Graph()
G.add_node('N1',n_type=1)
G.add_node('N2',n_type=1)
G.add_node('N3',n_type=2)
G.add_edges_from([('N3','N1'),('N3','N2')])

If I use the nx.average_neighbor_degree(G) function from NetworkX I get the following results.

{'N1': 2.0, 'N2': 2.0, 'N3': 1.0}

However, I would like to obtain the average neighbor degree considering only one type of node. For example, the average neighbor degree for the attribute when it takes the value of 1 should be:

{'N1': 0.0, 'N2': 0.0, 'N3': 1.0}

This, since node N3 is the only one that has neighbors with attribute n_type=1 and the average of it's neighbors is Degree(N1)+Degree(N2)/2 = 1+1/2 = 1

Any suggestions?

1 Answers

Checking the source code and tweaking it a bit I could come up with this. Hope it could help.

import networkx as nx

def get_average_nbr_deg_by_type(G, node_type):
    avg = {}
    for n, deg in G.degree:
        nbrs_deg = [d for n, d in G.degree(G[n]) if G.nodes[n]['n_type'] == node_type]
        deg = len(nbrs_deg)
        if deg == 0:
            deg = 1
        avg[n] = sum(nbrs_deg) / float(deg)

    return avg
get_average_nbr_deg_by_type(G, node_type=1)
# outputs {'N1': 0.0, 'N2': 0.0, 'N3': 1.0}
Related