Reputation: 385
I have a sample dataframe with a column for 'to', a column for 'from' and several columns for features relating to either the 'to' or 'from' colum.
I used G = nx.from_pandas_edgelist(df, source='to', target='from',edge_attr=True)
to convert the dataframe to a NetworkX graph. I used edge_attr=True
because I would like to keep the features for future analysis.
I want to calculate the number of neighbours for each point, so I used neighbours = nx.all_neighbors(G,0)
however, I get the error 'The node 0 is not in the graph.'
I'm not sure what I'm doing wrong.
import pandas as pd
import networkx as nx
df = pd.DataFrame({'to':[78,18,94,55,68,57,78,8],
'from':[18,78,35,14,57,68,57,17],
'to_Attribute_1':[18,78,35,14,57,68,57,17],
'to_Attribute_2':[18,78,35,14,57,68,57,17],
'from_Attribute_1':[18,78,35,14,57,68,57,17],
'from_Attribute_2':[18,78,35,14,57,68,57,17],
})
G = nx.from_pandas_edgelist(df, source='to', target='from',edge_attr=True)
[e for e in G.edges]
neighbours = nx.all_neighbors(G,0)
Upvotes: 1
Views: 661
Reputation: 260690
You should loop over the graph's nodes:
neighbours = {n: len(list(nx.all_neighbors(G, n))) for n in G.nodes}
Output (node -> number of neighbors):
{78: 2, 18: 1, 94: 1, 35: 1, 55: 1, 14: 1, 68: 1, 57: 2, 8: 1, 17: 1}
Upvotes: 1