【问题标题】:NetworkX - Setting node attributes from dataframeNetworkX - 从数据框设置节点属性
【发布时间】:2019-02-02 21:59:04
【问题描述】:

我无法确定如何从数据框中的列向网络中的节点添加属性。

我在下面提供了我的数据框示例,总共大约有 10 列,但我在创建网络时只使用下面显示的 5 列。

不幸的是,目前我只能让边缘属性与我的网络一起使用,我正在这样做,如下所示:

g = nx.from_pandas_dataframe(df, 'node_from', 'node_to', edge_attr=['attribute1','attribute2','attribute3'])

网络将是一个有向网络。下面数据框中显示的属性是“node_from”节点的属性。 “node_to”节点有时显示为“node_from”节点。 df_attributes_only 表中显示了网络中所有可能出现的节点及其各自的属性。

df_relationship:

node_from:  node_to: ........ attribute1:   attribute2:   attribute3:
    jim      john    ........    tall          red             fat
    ...

所有列的值都是单词,而不是数字。

我还有另一个数据框,其中包含每个可能的节点及其属性:

df_attributes_only:

id:   attribute1:   attribute2:     attribute3:
jim      tall          red             fat
john     small         blue            fat
...

我基本上需要将上述三个属性分配给它们各自的 id,因此每个节点都附加了它们的 3 个属性。

非常感谢任何有关如何让节点属性与我的网络一起使用的帮助。

【问题讨论】:

  • 关于属性的快速问题。它们是在描述它们连接的节点,还是以某种方式描述了关系?例如,吉姆又高又胖?这是否以某种方式描述了吉姆与其他事物之间的关系?是否存在可能存在多个属性的情况,例如,jim 是否有另一个条目显示关系,但将他列为又矮又胖?吉姆会有多重关系吗?

标签: python pandas networkx


【解决方案1】:

从Networkx 2.0开始,您可以在nx.set_node_attributes 中输入字典字典来设置多个节点的属性。与手动迭代每个节点相比,这是一种更加简化的方法。外部字典键代表每个节点,内部字典键对应于您要为每个节点设置的属性。像这样的:

attrs = {
    node0: {attr0: val00, attr1: val01},
    node1: {attr0: val10, attr1: val11},
    node2: {attr0: val20, attr1: val21},
}
nx.set_node_attributes(G, attrs)

您可以在documentation 中找到更多详细信息。


使用您的示例,假设您的索引是 id,您可以将节点属性的数据框 df_attributes_only 转换为这种格式并添加到您的图表中:

df_attributes_only = pd.DataFrame(
    [['jim', 'tall', 'red', 'fat'], ['john', 'small', 'blue', 'fat']],
    columns=['id', 'attribute1', 'attribute2', 'attribute3']
)
node_attr = df_attributes_only.set_index('id').to_dict('index')
nx.set_node_attributes(g, node_attr)

g.nodes['jim']


>>> {'attribute1': 'tall', 'attribute2': 'red', 'attribute3': 'fat'}

【讨论】:

    【解决方案2】:

    nx.from_pandas_dataframe(以及最新稳定版本 2.2 中的 from_pandas_edgelist),从概念上将边列表转换为图。即,数据框中的每一行代表一条边,它是一对2个不同的节点。

    使用此 API 无法读取节点的属性。这是有道理的,因为每一行都有两个不同的节点,并且为不同的节点保留特定的列会很麻烦并且可能导致差异。例如,考虑以下数据框:

    node_from node_to src_attr_1 tgt_attr_1
      a         b         0         3
      a         c         2         4
    

    节点 a 的 'src_attr_1' 值应该是多少?是0还是2?此外,我们需要为每个属性保留两列(因为它是节点属性,每条边上的两个节点都应该有它)。在我看来,支持它是不好的设计,我想这就是 NetworkX API 不支持的原因。

    df转成图后,仍然可以读取节点的属性,如下:

    import networkx as nx
    import pandas as pd
    
    # Build a sample dataframe (with 2 edges: 0 -> 1, 0 -> 2, node 0 has attr_1 value of 'a', node 1 has 'b', node 2 has 'c')
    d = {'node_from': [0, 0], 'node_to': [1, 2], 'src_attr_1': ['a','a'], 'tgt_attr_1': ['b', 'c']}
    df = pd.DataFrame(data=d)
    G = nx.from_pandas_edgelist(df, 'node_from', 'node_to')
    
    # Iterate over df rows and set the source and target nodes' attributes for each row:
    for index, row in df.iterrows():
        G.nodes[row['node_from']]['attr_1'] = row['src_attr_1']
        G.nodes[row['node_to']]['attr_1'] = row['tgt_attr_1']
    
    print(G.edges())
    print(G.nodes(data=True))
    

    编辑:

    如果您想拥有大量源节点的属性列表,您可以自动提取此列的字典,如下所示:

    #List of desired source attributes:
    src_attributes = ['src_attr_1', 'src_attr_2', 'src_attr_3']
    
    # Iterate over df rows and set source node attributes:
    for index, row in df.iterrows():
        src_attr_dict = {k: row.to_dict()[k] for k in src_attributes}    
        G.nodes[row['node_from']].update(src_attr_dict)
    

    【讨论】:

    【解决方案3】:

    这是基于@zohar.kom 的回答。有一种方法可以在没有迭代的情况下解决这个问题。这个答案可以优化。我假设属性描述了node_from。

    从边缘列表中的图开始(就像在@zohar.kom 的分析器中一样):

     G = nx.from_pandas_edgelist(df, 'node_from', 'node_to')
    

    您可以先添加节点和属性。

     # Create a mask with only the first records
     mask = ~df['node_from'].duplicated()
     # Get a list of nodes with attributes
     nodes = df[mask][['node_from','attribute1','attribute2','attribute3']]
    

    这个从dataframe中添加节点的方法来自this answer。

     # Add the attributes one at a time.
     attr_dict = nodes.set_index('node_from')['attribute1'].to_dict()
     nx.set_node_attributes(G,attr_dict,'attr1')
    
     attr_dict = nodes.set_index('node_from')['attribute2'].to_dict()
     nx.set_node_attributes(G,attr_dict,'attr2')
    
     attr_dict = nodes.set_index('node_from')['attribute3'].to_dict()
     nx.set_node_attributes(G,attr_dict,'attr3')
    

    与@zohar.kom 的结果相似,但迭代次数更少。

    【讨论】:

    • node from 的列名是什么?这就是该列中需要包含的内容。
    • TiAddendum,我意识到在发布此内容时我忘记了引号。我在答案中对其进行了编辑。
    • 是的,但是您的示例没有显示节点的详细信息将显示的任何地方。哪些字段有节点的数据?
    • 在示例中,您在源数据的单行中列出了 jim 和 john,属性字段中的属性为 tall、red 和 fat。这是否意味着 jim 和 john 都具有这些属性?如果不是,哪个列名存储 node_to 的属性?
    • 是的,您需要为nodes_to 添加数据。再多的代码都不会让你发明不存在的数据。添加后,您只需使用完全相同的代码替换 node_to 替换 node_from 和描述 node_to 的新字段替换描述 node_from 的 old_fileds。如果您正在查询数据并且有能力提取这些列,我觉得可能有更好的方法来解决整个过程,但我们没有足够的信息来进行调用。
    猜你喜欢
    • 2016-05-04
    • 1970-01-01
    • 2015-05-08
    • 2011-04-28
    • 2018-05-08
    • 1970-01-01
    • 2012-03-27
    • 2017-03-29
    • 1970-01-01
    相关资源
    最近更新 更多