2

I am working with networks as graph of the interaction between characters in Spanish theatre plays. Here a visualisation:

Network of Bodas de Sangre, by Lorca

I passed several attributes of the nodes (characters) as a dataframe to the network, so that I can use this values (for example the color of the nodes is set by the gender of the character). I want to calculate with NetworkX different values for each nodes (degree, centrality, betweenness...); then, I would like to output as a DataFrame both my attributes of the nodes and also the values calculated with NetworkX. I know I can ask for specific attributes of the nodes, like:

nx.get_node_attributes(graph,'degree')

And I could build a DataFrame using that, but I wonder if there is no a more elegant solution. I have tried also:

nx.to_dict_of_dicts(graph)

But this outputs only the edges and not the information about the nodes.

So, any help, please? Thanks!

2
  • With networkx >= 1.11 you have nx.to_pandas_dataframe Commented Oct 26, 2017 at 11:45
  • Hi! This creates the adjacency matrix, it doesn't print the attributes. I have been reading the parameters and I don't think this function is useful for that. Commented Nov 2, 2017 at 6:57

1 Answer 1

5

If I understand your question correctly, you want to have a DataFrame which has nodes and some of the attribute of each node.

G = nx.Graph()
G.add_node(1, {'x': 11, 'y': 111})
G.add_node(2, {'x': 22, 'y': 222})

You can use list comprehension as follow to get specific node attributes:

pd.DataFrame([[i[0], i[1]['x'], i[1]['y']] for i in G.nodes(data=True)]
             , columns=['node_name', 'x', 'y']).set_index('node_name')


#           x   y
#node_name      
#1         11   111
#2         22   222

or if there are many attributes and you need all of them, this could be a better solution:

pd.DataFrame([i[1] for i in G.nodes(data=True)], index=[i[0] for i in G.nodes(data=True)])
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks! The last solution was exactly what I was looking for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.