I have a data frame like below:
df=
Parent Child
1087 4
1087 5
1087 25
1096 25
1096 26
1096 27
1096 4
1144 25
1144 26
1144 27
I have tried this below code.. but not providing directed graph just giving graph which is not clear picture
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with 4 connections
df = pd.DataFrame([[k, i] for k, v in data.items() for i in v],
columns=['parent', 'child'])
# Build your graph
G = nx.from_pandas_edgelist(df, 'parent', 'child')
# Plot it
nx.draw(G,pos=nx.spring_layout(G), with_labels=True)
plt.show()
I would like like to convert this data frame into directed graph where source is parent and target is child.
Thanks in advance....
You need to specify the create_using
parameter in from_pandas_edgelist :
G = nx.from_pandas_edgelist(df, 'parent', 'child', create_using=nx.DiGraph())
The type of G
after is <class 'networkx.classes.digraph.DiGraph'>
and the edges are:
(1144, 25)
(1144, 26)
(1144, 27)
(1096, 25)
(1096, 26)
(1096, 27)
(1096, 4)
(1087, 25)
(1087, 4)
(1087, 5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.