Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create a directed graph using from_pandas_dataframe from networkx

Tags:

I'm learning networkx library and use twitter retweet directed graph data. I first read the datasets into pandas df (columns are 'from','to','weight') and wanted to put a first 300 rows(retweet) into a graph using below code:

tw_small = nx.from_pandas_dataframe(edges_df[:300],source='from',
                                   target='to',edge_attr=True)

I thought that it correctly created a graph but when I run tw_small.is_directed(), it says False(undirected graph) and I drew a graph using nx.draw() but it doesn't show the direction either.

Could someone help me find a correct way to make a directed graph?

Thanks.

like image 285
user3368526 Avatar asked Jun 18 '17 03:06

user3368526


People also ask

How can you tell if a graph is directed by NetworkX?

To check if the graph is directed you can use nx.is_directed(G) , you can find the documentation here. 'weight' in G[1][2] # Returns true if an attribute called weight exists in the edge connecting nodes 1 and 2.


2 Answers

Add the optional keyword argument create_using=nx.DiGraph(),

tw_small = nx.from_pandas_dataframe(edges_df[:300],source='from',
                                   target='to',edge_attr=True,
                                   create_using=nx.DiGraph())
like image 126
Aric Avatar answered Oct 04 '22 08:10

Aric


Instead of a dataframe you can write edgelist, it works for me, it shows me an error when I used from_pandas_dataframe : "AttributeError: module 'networkx' has no attribute 'from_pandas_dataframe"

Solution :

Graph = nx.from_pandas_edgelist(df,source='source',target='destination', edge_attr=None, create_using=nx.DiGraph())

You can test if your graph is directed or not using: nx.is_directed(Graph). You will get True.

like image 40
Hamdi Tarek Avatar answered Oct 04 '22 09:10

Hamdi Tarek