【问题标题】:Node's attributes from a different dataset来自不同数据集的节点属性
【发布时间】:2021-09-19 00:57:57
【问题描述】:

我需要合并来自不同数据集的一些信息来构建一个包含节点、边和节点属性的数据集。

第一个数据集(df1)是这样的:

Node     Edge
A         B
A         D
B         N
B         A
B         X
S         C

第二个数据集包括唯一节点及其属性:

Node    Attribute
A           -1
B           0
C           -1.5
D           1
...
N           1
... 
X           0
Y           -1.5
W          -1.5
Z           1

我想使用第一个数据集 (df1) 中的链接创建一个图形,根据属性值对节点进行着色:

 - if -1.5 then grey    
 - if -1 then red
 - if 0 then orange
 - if 1 then yellow
 - if 1.5 then green    

为了构建我可以使用的图表

G = nx.from_pandas_edgelist(edges, source='Node', target='Edge')

然后我需要设置上述分配颜色的规则并将它们添加为节点的属性。 我的问题是如何将这些规则包含在节点的属性中。

【问题讨论】:

    标签: python pandas networkx


    【解决方案1】:

    主要问题是将属性 DataFrame 变成更有用的东西。我们可以通过set_index到Node创建一个Node到color的映射,map将当前属性数值转换成color:

    import networkx as nx
    import pandas as pd
    
    edges_df = pd.DataFrame({
        'Node': ['A', 'A', 'B', 'B', 'B', 'S'],
        'Edge': ['B', 'D', 'N', 'A', 'X', 'C']
    })
    
    # Abridged but contains values for all nodes in `edges_df`
    attributes_df = pd.DataFrame({
        'Node': ['A', 'B', 'C', 'D', 'N', 'S', 'X'],
        'Attribute': [-1, 0, -1.5, 1, 1, 1.5, 0]
    })
    
    mapper = {-1.5: 'grey', -1: 'red', 0: 'orange', 1: 'yellow', 1.5: 'green'}
    colour_map = attributes_df.set_index('Node')['Attribute'].map(mapper)
    

    colour_map:

    Node
    A       red
    B    orange
    C      grey
    D    yellow
    N    yellow
    S     green
    X    orange
    Name: Attribute, dtype: object
    

    *注意:在上述属性数据集中,值1.5 和节点S 都没有表示,因此所有节点都带有颜色,并且所有颜色都表示Sattributes_df 中设置为1.5


    colour_map 然后可以用于set_node_attributes

    G = nx.from_pandas_edgelist(edges_df, source='Node', target='Edge')
    # Add Attribute to each node
    nx.set_node_attributes(G, colour_map, name="colour")
    
    # Then draw with colours based on attribute values:
    nx.draw(G, 
            node_color=nx.get_node_attributes(G, 'colour').values(),
            with_labels=True)
    

    或者我们可以通过reindexing 基于图形节点直接使用系列(不创建节点属性),以确保颜色以与G.nodes() 中相同的顺序出现,这样可以确保正确的颜色与正确的颜色对齐节点:

    G = nx.from_pandas_edgelist(edges_df, source='Node', target='Edge')
    
    # Then draw with colours based on the Series:
    nx.draw(G, 
            node_color=colour_map.reindex(G.nodes()),
            with_labels=True)
    

    无论哪种方法,我们都会得到如下图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多