简体   繁体   English

python数据框的有向图

[英]directed graph with python dataframe

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 : 您需要在from_pandas_edgelist中指定create_using参数:

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: 之后的G的类型为<class 'networkx.classes.digraph.DiGraph'> ,并且边为:

(1144, 25)
(1144, 26)
(1144, 27)
(1096, 25)
(1096, 26)
(1096, 27)
(1096, 4)
(1087, 25)
(1087, 4)
(1087, 5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM