23

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.

user3368526
  • 2,168
  • 10
  • 37
  • 52

2 Answers2

44

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())
Aric
  • 24,511
  • 5
  • 78
  • 77
  • 1
    Thank you. The syntax for the create_using agrument was not clearly explained in the documentation. – SummerEla Aug 10 '18 at 23:46
  • I know it's been a while, but `from_pandas_datafarme` has been deprecated, how would you do it with more current tools? – Ofek Glick Sep 27 '21 at 20:54
  • 3
    @OfekGlick, not sure if you're still looking for this, but you would use `from_pandas_edgelist`, so it would be `G = nx.from_pandas_edgelist(edges_df, source='from', target='to', edge_attr=True, create_using=nx.DiGraph())` (which is what the other solution below by Hamdi Tarek is saying). – user6386471 Nov 17 '21 at 14:01
12

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.

Luis Cazares
  • 3,495
  • 8
  • 22
Hamdi Tarek
  • 141
  • 1
  • 5