代码之家  ›  专栏  ›  技术社区  ›  Edward

将熊猫数据帧转换为定向网络多图

  •  1
  • Edward  · 技术社区  · 7 年前

    我有一个数据框架,如下所示。

    import pandas as pd
    import networkx as nx
    
    df = pd.DataFrame({'source': ('a','a','a', 'b', 'c', 'd'),'target': ('b','b','c', 'a', 'd', 'a'), 'weight': (1,2,3,4,5,6) })
    

    我想把它转换成定向网络多重图。我愿意

    G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight'])
    

    &得到

    G.edges(data = True)
    [('d', 'a', {'weight': 6}),
     ('d', 'c', {'weight': 5}),
     ('c', 'a', {'weight': 3}),
     ('a', 'b', {'weight': 4})]
    G.is_directed(), G.is_multigraph()
    (False, False)
    

    但我想得到

    [('d', 'a', {'weight': 6}),
     ('c', 'd', {'weight': 5}),
     ('a', 'c', {'weight': 3}),
     ('b', 'a', {'weight': 4}),
    ('a', 'b', {'weight': 2}),
    ('a', 'b', {'weight': 4})]
    

    我在此中找不到定向多图表的参数 manual . 我可以拯救 df 作为TXT和使用 nx.read_edgelist() 但不方便

    2 回复  |  直到 7 年前
        1
  •  1
  •   Dani Mesejo    7 年前

    如需定向多图表,可以执行以下操作:

    import pandas as pd
    import networkx as nx
    
    df = pd.DataFrame(
        {'source': ('a', 'a', 'a', 'b', 'c', 'd'),
         'target': ('b', 'b', 'c', 'a', 'd', 'a'),
         'weight': (1, 2, 3, 4, 5, 6)})
    
    
    M = nx.from_pandas_edgelist(df, 'source', 'target', ['weight'], create_using=nx.MultiDiGraph())
    print(M.is_directed(), M.is_multigraph())
    
    print(M.edges(data=True))
    

    产量

    True True
    [('a', 'c', {'weight': 3}), ('a', 'b', {'weight': 1}), ('a', 'b', {'weight': 2}), ('c', 'd', {'weight': 5}), ('b', 'a', {'weight': 4}), ('d', 'a', {'weight': 6})]
    
        2
  •  3
  •   Unni Summer_More_More_Tea    7 年前

    使用 create_using 参数:

    create_using (networkx图)使用指定的图作为结果。默认值为 Graph()

    G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight'], create_using=nx.DiGraph())